#!/usr/bin/env bash
# freezeos-usb-creator — launcher + dependency bootstrapper for the standalone
# FreezeOS Install-USB creator (website download edition, for a Debian-based box).
#
# WHY a bash launcher: the GUI needs python3-gi + GTK, which may be absent on the
# friend's machine. Python can't import Gtk before those are installed, so the
# APT bootstrap MUST happen here (bash), before the Python GUI is exec'd.
#
# Run:  ./freezeos-usb-creator          (prompts for sudo when it needs root)
set -euo pipefail

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
APP="$HERE/freezeos_usb_creator.py"

RED='\033[0;31m'; GRN='\033[0;32m'; BLU='\033[0;34m'; YLW='\033[1;33m'; NC='\033[0m'
say()  { echo -e "${BLU}[usb-creator]${NC} $*"; }
ok()   { echo -e "${GRN}[  ok]${NC} $*"; }
warn() { echo -e "${YLW}[warn]${NC} $*"; }
die()  { echo -e "${RED}[fail]${NC} $*" >&2; exit 1; }

# ── 1. Sanity: Debian-family + apt ──────────────────────────────────────────
command -v apt-get >/dev/null 2>&1 || die "This tool needs a Debian/Ubuntu-based system (apt-get not found)."

# ── 2. Dependency check + apt install of anything missing ───────────────────
# Map: binary/GI-namespace we need  →  Debian package that provides it.
# GTK stack + partitioning/format/download tools + polkit (for the root write).
declare -A PKG=(
  [python3]=python3
  [gi:Gtk]=python3-gi
  [gi:Gtk3]=gir1.2-gtk-3.0
  [sgdisk]=gdisk
  [mkfs.vfat]=dosfstools
  [partprobe]=parted
  [wipefs]=util-linux
  [lsblk]=util-linux
  [curl]=curl
  [pkexec]=policykit-1
  [rsync]=rsync
  [eject]=eject
)

have() {
  case "$1" in
    gi:Gtk)  python3 -c 'import gi; gi.require_version("Gtk","3.0"); from gi.repository import Gtk' 2>/dev/null ;;
    gi:Gtk3) python3 -c 'import gi; gi.require_version("Gtk","3.0")' 2>/dev/null ;;
    *)       command -v "$1" >/dev/null 2>&1 ;;
  esac
}

MISSING_PKGS=()
for key in "${!PKG[@]}"; do
  if ! have "$key"; then
    MISSING_PKGS+=("${PKG[$key]}")
  fi
done
# de-dup
if [ "${#MISSING_PKGS[@]}" -gt 0 ]; then
  mapfile -t MISSING_PKGS < <(printf '%s\n' "${MISSING_PKGS[@]}" | sort -u)
  say "Installing missing dependencies: ${MISSING_PKGS[*]}"
  SUDO=""; [ "$(id -u)" -ne 0 ] && SUDO="sudo"
  $SUDO apt-get update -qq || warn "apt-get update failed — trying install anyway"
  $SUDO apt-get install -y "${MISSING_PKGS[@]}" || die "Dependency install failed. Install manually: apt-get install ${MISSING_PKGS[*]}"
  ok "Dependencies installed."
else
  ok "All dependencies present."
fi

# ── 3. Launch the GUI as the normal user (root writes go through pkexec) ─────
[ -f "$APP" ] || die "Missing $APP (incomplete download?)"
export FREEZEOS_USB_HELPER="$HERE/usb-helper.sh"
exec python3 "$APP" "$@"
