#!/bin/bash

# ShiftOS Pre-Installation Environment Setup

OS_NAME="ShiftOS"
INSTALL_DIR="/tmp/shiftos_core"
HELPER_DIR=""

echo "Initializing $OS_NAME Pre-Installation Environment..."

# 1. Security & Integrity Checks
if [ "$EUID" -ne 0 ]; then
    echo "Error: This installer must be run as root to manage dependencies and install the OS."
    echo "Please run the script again using: sudo ./shiftos-installer.sh"
    exit 1
fi

# 2. Locate Helper Scripts Phase
echo -n "Locating installation modules... "

# Prioritize local directories for testing, then check RPM locations
SEARCH_PATHS=(
    "$(dirname "$(realpath "$0")")"
    "$PWD"
    "/usr/libexec/shiftos-installer"
)

for path in "${SEARCH_PATHS[@]}"; do
    if [ -f "$path/format-install.sh" ] && [ -f "$path/firstboot-install.sh" ]; then
        HELPER_DIR="$path"
        break
    fi
done

# Fallback: Broad search of standard filesystem paths if arrays fail
if [ -z "$HELPER_DIR" ]; then
    echo -n "Standard paths failed, scanning filesystem... "
    FOUND_PATH=$(find /usr /opt /home -type f -name "format-install.sh" 2>/dev/null | head -n 1)
    if [ -n "$FOUND_PATH" ]; then
        HELPER_DIR="$(dirname "$FOUND_PATH")"
    fi
fi

if [ -z "$HELPER_DIR" ]; then
    echo "Failed!"
    whiptail --title "Critical Error" --msgbox "Could not locate the required installation modules (format-install.sh) anywhere on the filesystem.\n\nInstallation aborted." 10 60
    exit 1
else
    echo "Found at $HELPER_DIR"
    sleep 1
fi

# 3. Repository Management Phase
echo "Checking openSUSE Tumbleweed repositories..."

check_and_add_repo() {
    local alias=$1
    local url=$2
    echo -n "  -> Checking for repository '$alias'... "
    
    if ! zypper lr -u 2>/dev/null | grep -q "$url"; then
        echo "Not found. Adding..."
        zypper ar -f "$url" "$alias" > /dev/null 2>&1
        REPO_ADDED=1
    else
        echo "Found."
    fi
}

REPO_ADDED=0
check_and_add_repo "repo-oss" "http://download.opensuse.org/tumbleweed/repo/oss/"
check_and_add_repo "repo-non-oss" "http://download.opensuse.org/tumbleweed/repo/non-oss/"
check_and_add_repo "repo-update" "http://download.opensuse.org/update/tumbleweed/"
check_and_add_repo "shiftos-package-center" "https://repo.shiftos.network/tumbleweed/"

if [ "$REPO_ADDED" -eq 1 ]; then
    echo "Refreshing repository caches..."
    zypper --quiet --non-interactive --gpg-auto-import-keys refresh
fi

# 4. Dependency Checking Phase
echo "Checking required installation dependencies..."

check_dependency() {
    local cmd=$1
    local pkg=$2
    
    echo -n "  -> Checking for $cmd (package: $pkg)... "
    if ! command -v "$cmd" &> /dev/null; then
        echo "Not found. Installing $pkg..."
        zypper --non-interactive --gpg-auto-import-keys install -y "$pkg" > /dev/null 2>&1
        
        if ! command -v "$cmd" &> /dev/null; then
            echo "Error: Failed to install $pkg automatically. Please install manually."
            exit 1
        fi
        echo "     Successfully installed $pkg."
    else
        echo "Found."
    fi
}

check_dependency "whiptail" "newt"           
check_dependency "parted" "parted"           
check_dependency "rsync" "rsync"             
check_dependency "mkfs.ext4" "e2fsprogs"     
check_dependency "mkfs.fat" "dosfstools"     

echo "All dependencies and repositories are satisfied. Launching UI..."
sleep 2

# 5. Welcome Message/Screen
whiptail --title "ShiftOS Installer" --msgbox "Welcome to the $OS_NAME Installer/Setup!\n\nAll system dependencies have been verified.\n\nPress OK to begin preparing your environment." 12 60

# 6. Drive Selection Phase
DRIVE_LIST=()

while read -r name size model; do
    if [ -z "$model" ]; then model="Virtual/Unknown Disk"; fi
    DRIVE_LIST+=("/dev/$name" "$size - $model" "OFF")
done < <(lsblk -d -n -o NAME,SIZE,MODEL -e 7,11 2>/dev/null)

if [ ${#DRIVE_LIST[@]} -eq 0 ]; then
    whiptail --title "Critical Error" --msgbox "No suitable hard drives detected on this system!\n\nInstallation cannot continue." 10 50
    exit 1
fi

TARGET_DRIVE=$(whiptail --title "Target Drive Selection" --radiolist \
    "Select the target drive for $OS_NAME installation.\nUse ARROW KEYS to navigate, SPACE to select, and ENTER to confirm.\n\nWARNING: All data on the selected drive will eventually be erased!" \
    18 70 6 "${DRIVE_LIST[@]}" 3>&1 1>&2 2>&3)

if [ $? -ne 0 ]; then
    whiptail --title "Canceled" --msgbox "Installation canceled by user." 8 40
    exit 1
fi

if [ -z "$TARGET_DRIVE" ]; then
    whiptail --title "Error" --msgbox "No drive selected. Installation aborted." 8 40
    exit 1
fi

# 7. Create Installation Directory (Progress Bar)
{
    echo "0"
    sleep 1
    
    echo "XXX"
    echo "Creating Installation Directory at $INSTALL_DIR..."
    echo "XXX"
    echo "50"
    
    mkdir -p "$INSTALL_DIR"
    sleep 1
    
    echo "XXX"
    echo "Directory creation complete."
    echo "XXX"
    echo "100"
    sleep 1
} | whiptail --title "Working" --gauge "Preparing $TARGET_DRIVE..." 8 60 0

# 8. Final Confirmation & Script Handoff
if whiptail --title "Confirm Installation" --yesno "Ready to install $OS_NAME Core to: $TARGET_DRIVE\n\nWARNING: Proceeding will permanently erase ALL DATA on this drive. Are you absolutely sure you wish to continue?" 12 60; then
    
    whiptail --title "Proceeding" --infobox "Launching ShiftOS Disk Formatter...\nHanding off to format-install.sh" 8 50
    sleep 2
    
    # Hand off using the dynamically discovered HELPER_DIR, passing it down as the 3rd argument
    exec "$HELPER_DIR/format-install.sh" "$TARGET_DRIVE" "$INSTALL_DIR" "$HELPER_DIR"
    
else
    whiptail --title "Canceled" --msgbox "Installation canceled by user. Your disk has not been modified." 8 50
    exit 0
fi
