#!/usr/bin/env bash
# build.sh — build the M-Archy Arch Linux ISO
#
# Usage:
#   bash build.sh [--preconf [FILE]] [OUT_DIR]
#
#   --preconf        Embed ~/answerfile.json into the ISO at /answerfile.json
#   --preconf FILE   Embed the specified answerfile instead
#   OUT_DIR          Output directory (default: ~/m-archy-out, or $OUT_DIR env)

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DOTFILES_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"

# ── Argument parsing ───────────────────────────────────────────────────────────
PRECONF_FILE=""
OUT_ARG=""

while [[ $# -gt 0 ]]; do
    case "$1" in
        --preconf)
            # Optional next arg: a file path (doesn't start with -)
            if [[ $# -gt 1 && "${2:0:1}" != "-" ]]; then
                PRECONF_FILE="$2"; shift
            else
                PRECONF_FILE="$HOME/answerfile.json"
            fi
            shift
            ;;
        --preconf=*)
            PRECONF_FILE="${1#--preconf=}"
            shift
            ;;
        -*)
            echo "Unknown flag: $1" >&2; exit 1
            ;;
        *)
            OUT_ARG="$1"; shift
            ;;
    esac
done

WORK_DIR="${WORK_DIR:-$HOME/m-archy-build}"
OUT_DIR="${OUT_ARG:-${OUT_DIR:-$HOME/m-archy-out}}"
PROFILE="$WORK_DIR/profile"
RELENG="/usr/share/archiso/configs/releng"

if ! command -v mkarchiso &>/dev/null; then
    echo "Installing archiso..."
    sudo pacman -S --noconfirm archiso
fi

[[ -d "$RELENG" ]] || { echo "ERROR: $RELENG not found — is archiso installed?"; exit 1; }

# Validate answerfile early if --preconf was given
if [[ -n "$PRECONF_FILE" ]]; then
    [[ -f "$PRECONF_FILE" ]] \
        || { echo "ERROR: answerfile not found: $PRECONF_FILE"; exit 1; }
    command -v jq &>/dev/null \
        && jq empty "$PRECONF_FILE" \
        || echo "Warning: jq not available — skipping answerfile JSON validation"
    echo "Answerfile to embed: $PRECONF_FILE"
fi

rm -rf "$WORK_DIR"
mkdir -p "$WORK_DIR" "$OUT_DIR"

echo "Copying releng base profile..."
cp -r "$RELENG" "$PROFILE"

echo "Applying M-Archy overlay..."
cp -r "$SCRIPT_DIR/overlay/airootfs/." "$PROFILE/airootfs/"

echo "Replacing profiledef..."
cp "$SCRIPT_DIR/overlay/profiledef.sh" "$PROFILE/profiledef.sh"

echo "Adding extra packages..."
while IFS= read -r pkg || [[ -n "$pkg" ]]; do
    [[ -z "$pkg" || "$pkg" == \#* ]] && continue
    grep -qxF "$pkg" "$PROFILE/packages.x86_64" || echo "$pkg" >> "$PROFILE/packages.x86_64"
done < "$SCRIPT_DIR/overlay/packages.extra"

echo "Embedding installer scripts..."
mkdir -p "$PROFILE/airootfs/root/installer"
cp "$DOTFILES_DIR/setup/archbaseos-guided-install.sh" "$PROFILE/airootfs/root/installer/"
cp "$DOTFILES_DIR/setup/arch-autoinstall.sh"          "$PROFILE/airootfs/root/installer/"
cp "$DOTFILES_DIR/setup/reset-arch.sh"                "$PROFILE/airootfs/root/installer/"

chmod 755 \
    "$PROFILE/airootfs/root/launch.sh" \
    "$PROFILE/airootfs/root/.automated_script.sh" \
    "$PROFILE/airootfs/usr/local/bin/install-arch" \
    "$PROFILE/airootfs/root/installer/"*.sh

# ── Embed answerfile (--preconf) ───────────────────────────────────────────────
if [[ -n "$PRECONF_FILE" ]]; then
    echo "Embedding answerfile: $PRECONF_FILE → /answerfile.json"
    install -m 644 "$PRECONF_FILE" "$PROFILE/airootfs/answerfile.json"
fi

echo "Building ISO (this may take a while)..."
sudo mkarchiso -v -w "$WORK_DIR/mkarchiso" -o "$OUT_DIR" "$PROFILE"
sudo chmod -R 777 "$WORK_DIR" "$OUT_DIR"
sudo chown -R "$(id -u):$(id -g)" "$WORK_DIR" "$OUT_DIR"

echo
echo "Done."
ls -lh "$OUT_DIR/"*.iso 2>/dev/null || true

if [[ -n "$PRECONF_FILE" ]]; then
    echo "Answerfile embedded — automated install will activate on boot."
else
    echo "No answerfile — guided (manual) installer will start automatically on boot."
fi
