#!/bin/bash
# ==============================================================================
# karch - Arch Linux Installer
# Entry point — dispatches Phase 1 (live ISO) and Phase 2 (chroot)
# ==============================================================================
set -uo pipefail

# --- Resolve script directory ------------------------------------------------
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# --- Source common library ---------------------------------------------------
# shellcheck disable=SC1091
source "${SCRIPT_DIR}/lib/common.sh"

# --- Parse arguments ---------------------------------------------------------
IN_CHROOT=false
RESUME=false

for arg in "$@"; do
    case "$arg" in
        --chroot) IN_CHROOT=true ;;
        --resume) RESUME=true ;;
        --help|-h)
            echo "Usage: $0 [--resume]"
            echo ""
            echo "  --resume    Resume from the last successfully completed module"
            echo ""
            echo "Run this script from the Arch Linux live ISO environment."
            exit 0
            ;;
        *)
            msg_error "Unknown argument: $arg"
            exit 1
            ;;
    esac
done

# --- Root check --------------------------------------------------------------
if [[ $EUID -ne 0 ]]; then
    msg_error "This script must be run as root."
    exit 1
fi

# ==============================================================================
# Phase 2 — Inside chroot
# ==============================================================================
if [[ "$IN_CHROOT" == "true" ]]; then
    msg_info "=== karch Phase 2: Configuring installed system ==="

    PHASE2_MODULES=(
        locale
        timezone
        fonts
        pacman_conf
        user
        profile
        bootloader
    )

    for mod in "${PHASE2_MODULES[@]}"; do
        run_module "$mod" "$RESUME"
    done

    msg_ok "=== Phase 2 complete ==="

    # Clean up the copied script bundle
    rm -rf /root/karch

    exit 0
fi

# ==============================================================================
# Phase 1 — Live ISO environment
# ==============================================================================
msg_info "=== karch Phase 1: Preparing installation ==="

# Verify we're on the live ISO (basic sanity check)
if [[ ! -f /run/archiso/bootmnt/arch/boot/x86_64/vmlinuz-linux ]] && \
   [[ ! -d /run/archiso ]]; then
    dialog_yesno "Environment Check" \
        "This does not appear to be the Arch Linux live ISO.\n\nContinue anyway?" || exit 1
fi

# --- Phase 1 modules --------------------------------------------------------
# Network runs first (text-only prompts are fine for this one module).
run_module "network" "$RESUME"

# Now that we have internet, install dialog if missing and relaunch so every
# subsequent prompt gets the full TUI.
if ! command -v dialog &>/dev/null; then
    msg_info "Installing dialog for TUI prompts..."
    pacman -Sy --noconfirm dialog 2>/dev/null || true
    if command -v dialog &>/dev/null; then
        msg_ok "dialog installed — relaunching with TUI support..."
        # Mark network complete so --resume skips it on relaunch
        exec "${SCRIPT_DIR}/install.sh" --resume
    else
        msg_warn "dialog unavailable — continuing with text prompts."
    fi
fi

PHASE1_MODULES=(
    disk
    base
)

for mod in "${PHASE1_MODULES[@]}"; do
    run_module "$mod" "$RESUME"
done

msg_ok "=== Phase 1 complete: base system installed ==="

# --- Copy scripts into target for Phase 2 -----------------------------------
msg_info "Copying karch scripts into target system..."
mkdir -p /mnt/root/karch

# Use cp -a on the directory itself to avoid glob issues with hidden files or
# paths containing special characters.
cp -a "${SCRIPT_DIR}/." /mnt/root/karch/

# Ensure the env file is accessible inside the chroot
if [[ -f "$ENV_FILE" ]]; then
    cp "$ENV_FILE" /mnt/root/karch/karch.env
fi

# Verify critical files exist before entering chroot
if [[ ! -f /mnt/root/karch/install.sh ]]; then
    msg_error "FATAL: install.sh not found at /mnt/root/karch/ after copy."
    msg_error "Source was: ${SCRIPT_DIR}"
    ls -la /mnt/root/karch/ 2>/dev/null || msg_error "/mnt/root/karch/ does not exist."
    exit 1
fi
chmod +x /mnt/root/karch/install.sh

# --- Enter chroot for Phase 2 -----------------------------------------------
msg_info "Entering chroot for Phase 2..."

CHROOT_ARGS=(--chroot)
if [[ "$RESUME" == "true" ]]; then
    CHROOT_ARGS+=(--resume)
fi

# Verify bash exists inside the chroot
if [[ ! -x /mnt/usr/bin/bash ]]; then
    msg_error "FATAL: /usr/bin/bash not found inside /mnt — pacstrap may have failed."
    exit 1
fi

arch-chroot /mnt /usr/bin/bash /root/karch/install.sh "${CHROOT_ARGS[@]}"
chroot_rc=$?

if [[ $chroot_rc -ne 0 ]]; then
    msg_error "Phase 2 failed inside chroot (exit code: $chroot_rc)."
    msg_error "Check the output above for details."
    dialog_yesno "Phase 2 Failed" \
        "The chroot configuration phase failed.\n\nWould you like to drop into a shell inside the chroot to debug?" \
        && arch-chroot /mnt /usr/bin/bash
    exit 1
fi

# --- Cleanup and reboot prompt -----------------------------------------------
msg_ok "=== Installation complete ==="

# Re-read env from the live ISO's copy (chroot copy was cleaned up)
# Phase 1 values (PART_SWAP, DISK, etc.) are still in the original file
if [[ -f "$ENV_FILE" ]]; then
    source_env
fi
if [[ -n "${PART_SWAP:-}" ]]; then
    msg_info "Deactivating swap..."
    swapoff "$PART_SWAP" 2>/dev/null || true
fi

msg_info "Unmounting filesystems..."
umount -R /mnt 2>/dev/null || true

dialog_msgbox "Installation Complete" \
    "The Arch Linux installation is complete!\n\nThe system will be ready to use after reboot.\n\nRemove the installation media before rebooting."

dialog_yesno "Reboot" "Reboot now?" && reboot
