#!/usr/bin/env bash
set -euo pipefail
VERSION="0.2.6b"
CONFIRM="CONVERT_DEBIAN_TO_SENTINELOS"
LOG_DIR="/var/log/sentinelos"
STATE_DIR="/var/lib/sentinelos/conversion"
POLICY="/usr/share/sentinelos/conversion/policy.json"

usage() {
  cat <<EOF
sentinelos-convert-debian v$VERSION

Commands:
  --summary
  --preflight
  --plan
  --verify
  --report
  --run --mode desktop [options] --confirm $CONFIRM

Options for --run:
  --with-aegis
  --install-sentinel-suite
  --install-libreoffice
  --install-mate-apps
  --appearance sentinel-dark|sentinel-light

Converter mode does not wipe disks. Clean install is future ISO/live-installer only.
EOF
}

summary() {
  cat <<EOF
SentinelOS Debian Conversion
version: $VERSION
mode_supported: desktop
hardening_base: integrated
installer_gui_frontend: sentinelos-installer-gui
conversion_style: package-owned / auditable / explicit-confirmation
theme_baseline_expected: v0.2.5c or newer
background_preservation_expected: yes
aegis_install: optional
mandatory_aegis_runtime: no
sentinel_desktop_suite_option: yes
libreoffice_option: yes
mate_apps_option: yes
appearance_options: sentinel-dark sentinel-light
clean_install: disabled_iso_only
policy: $POLICY
EOF
}

is_debian() {
  [ -r /etc/os-release ] && . /etc/os-release && [ "${ID:-}" = "debian" -o "${ID_LIKE:-}" = "debian" ]
}

preflight() {
  echo "SentinelOS Debian Conversion Preflight"
  echo "version: $VERSION"
  echo "timestamp: $(date -Iseconds)"
  echo
  local ok=1
  if is_debian; then echo "debian: ok"; else echo "debian: warning/not-confirmed"; fi
  command -v dpkg >/dev/null 2>&1 && echo "dpkg: ok" || { echo "dpkg: missing"; ok=0; }
  command -v apt >/dev/null 2>&1 && echo "apt: ok" || echo "apt: warning/not-found"
  if command -v mate-session >/dev/null 2>&1 || dpkg -s mate-desktop-common >/dev/null 2>&1; then echo "mate_desktop: detected"; else echo "mate_desktop: warning/not-detected"; fi
  if command -v sentinelos-hardening >/dev/null 2>&1; then
    echo "hardening_tool: ok"
    sentinelos-hardening --verify >/tmp/sentinelos-convert-preflight-hardening.log 2>&1 || { sed 's/^/hardening_verify: /' /tmp/sentinelos-convert-preflight-hardening.log; ok=0; }
  else
    echo "hardening_tool: missing"; ok=0
  fi
  command -v sentinelos-installer-gui >/dev/null 2>&1 && echo "installer_gui: detected" || echo "installer_gui: warning/not-detected"
  command -v sentinelos-theme-base >/dev/null 2>&1 && echo "theme_base_tool: detected" || echo "theme_base_tool: warning/not-detected"
  command -v sentinelos-background-guard >/dev/null 2>&1 && echo "background_guard: detected" || echo "background_guard: warning/not-detected"
  command -v sentinelos-official-icon-baseline >/dev/null 2>&1 && echo "official_icon_baseline: detected" || echo "official_icon_baseline: warning/not-detected"
  [ "$ok" = "1" ] && echo "preflight: ok" || { echo "preflight: failed"; exit 1; }
}

plan() {
  cat <<'EOF'
SentinelOS Debian Conversion Plan

1. Preflight
2. State/log setup
3. Hardening base audit and safe apply with explicit confirmation
4. Branding/theme/icon verification
5. Optional application selection:
   - Sentinel Desktop Suite
   - LibreOffice
   - MATE desktop applications
6. Optional AEGIS Prime local assistant selection
7. Public appearance request:
   - SentinelOS Dark
   - SentinelOS Light
8. Final conversion report

Safety:
  - no disk wiping in converter mode
  - no clean install from converter mode
  - no root per-user wallpaper mutation
  - no root per-user MATE theme mutation
  - no mandatory AEGIS runtime
EOF
}

verify() {
  local ok=1
  [ -f "$POLICY" ] || { echo "missing: $POLICY"; ok=0; }
  command -v sentinelos-convert-debian >/dev/null 2>&1 || { echo "missing command: sentinelos-convert-debian"; ok=0; }
  command -v sentinelos-hardening >/dev/null 2>&1 || { echo "missing command: sentinelos-hardening"; ok=0; }
  sentinelos-hardening --verify >/tmp/sentinelos-convert-hardening-verify.log 2>&1 || { cat /tmp/sentinelos-convert-hardening-verify.log; ok=0; }
  [ "$ok" = "1" ] && echo "verify: ok" || { echo "verify: failed"; exit 1; }
}

report() {
  echo "SentinelOS Conversion Report"
  echo "version: $VERSION"
  echo "timestamp: $(date -Iseconds)"
  echo "policy: $POLICY"
  echo
  sentinelos-hardening --summary || true
  echo
  command -v sentinelos-installer-gui >/dev/null 2>&1 && sentinelos-installer-gui --summary || echo "installer_gui: not installed"
  echo
  command -v sentinelos-theme-base >/dev/null 2>&1 && sentinelos-theme-base --summary || echo "theme_base: not installed"
  echo
  command -v sentinelos-background-guard >/dev/null 2>&1 && sentinelos-background-guard --summary || echo "background_guard: not installed"
}

install_if_available() {
  local label="$1"; shift
  echo "$label:"
  if ! command -v apt-get >/dev/null 2>&1; then echo "  apt-get: not available"; return 0; fi
  DEBIAN_FRONTEND=noninteractive apt-get install -y "$@" || { echo "  warning: install did not complete for $label"; return 0; }
}

run_conversion() {
  local mode="" with_aegis="no" install_suite="no" install_libo="no" install_mate="no" appearance="sentinel-dark" confirm=""
  while [ $# -gt 0 ]; do
    case "$1" in
      --mode) mode="${2:-}"; shift 2 ;;
      --with-aegis) with_aegis="yes"; shift ;;
      --install-sentinel-suite) install_suite="yes"; shift ;;
      --install-libreoffice) install_libo="yes"; shift ;;
      --install-mate-apps) install_mate="yes"; shift ;;
      --appearance) appearance="${2:-}"; shift 2 ;;
      --confirm) confirm="${2:-}"; shift 2 ;;
      *) echo "ERROR: unknown argument $1" >&2; exit 2 ;;
    esac
  done
  [ "$(id -u)" = "0" ] || { echo "ERROR: conversion run requires root." >&2; exit 2; }
  [ "$mode" = "desktop" ] || { echo "ERROR: only --mode desktop is supported in v$VERSION" >&2; exit 2; }
  [ "$appearance" = "sentinel-dark" ] || [ "$appearance" = "sentinel-light" ] || { echo "ERROR: appearance must be sentinel-dark or sentinel-light" >&2; exit 2; }
  [ "$confirm" = "$CONFIRM" ] || { echo "ERROR: Missing confirmation. Use --confirm $CONFIRM" >&2; exit 2; }

  mkdir -p "$LOG_DIR" "$STATE_DIR"
  local stamp; stamp="$(date +%Y%m%d-%H%M%S)"
  local log="$LOG_DIR/conversion-$stamp.log"
  local report_file="$LOG_DIR/conversion-report-$stamp.txt"
  local state_file="$STATE_DIR/conversion-options-$stamp.json"

  cat > "$state_file" <<JSON
{
  "version": "$VERSION",
  "timestamp": "$(date -Iseconds)",
  "mode": "$mode",
  "with_aegis": "$with_aegis",
  "install_sentinel_suite": "$install_suite",
  "install_libreoffice": "$install_libo",
  "install_mate_apps": "$install_mate",
  "appearance": "$appearance",
  "clean_install": "disabled_iso_only",
  "disk_wipe": "no",
  "aegis_runtime_auto_enable": "no",
  "public_aegis_visual_wording": "hidden"
}
JSON

  {
    echo "SentinelOS Debian Conversion Run"
    echo "version: $VERSION"
    echo "timestamp: $(date -Iseconds)"
    echo "mode: $mode"
    echo "with_aegis: $with_aegis"
    echo "install_sentinel_suite: $install_suite"
    echo "install_libreoffice: $install_libo"
    echo "install_mate_apps: $install_mate"
    echo "appearance: $appearance"
    echo "clean_install: disabled_iso_only"
    echo "state_file: $state_file"
    echo
    echo "== Preflight =="; preflight; echo
    echo "== Hardening audit before apply =="; sentinelos-hardening --audit || true; echo
    echo "== Applying safe hardening baseline =="; sentinelos-hardening --apply-safe-baseline --confirm APPLY_SENTINELOS_HARDENING_BASE; echo
    echo "== Optional packages =="
    [ "$install_suite" = "yes" ] && install_if_available "Sentinel Desktop Suite" sentinel-program-manager sentinel-notes sentinel-browser sentinel-ledger sentinel-contacts sentinel-documents sentinel-password-vault sentinel-pantry sentinel-media-index sentinel-media-player sentinel-terminal sentinel-calculator sentinel-calendar sentinel-diary sentinel-jobs sentinel-maintenance sentinel-inventory sentinel-system-monitor sentinel-forge || echo "Sentinel Desktop Suite: skipped"
    [ "$install_libo" = "yes" ] && install_if_available "LibreOffice" libreoffice || echo "LibreOffice: skipped"
    [ "$install_mate" = "yes" ] && install_if_available "MATE desktop applications" mate-desktop-environment-extra || echo "MATE desktop applications: skipped"
    [ "$with_aegis" = "yes" ] && { install_if_available "AEGIS Prime local assistant" aegis-prime-suite aegis-sentinel-suite; echo "AEGIS runtime auto-enable: no"; } || echo "AEGIS Prime local assistant: skipped"
    echo
    echo "== Theme/background/icon verification =="
    command -v sentinelos-theme-base >/dev/null 2>&1 && sentinelos-theme-base --verify || echo "theme_base: not installed or verify warning"
    command -v sentinelos-background-guard >/dev/null 2>&1 && sentinelos-background-guard --verify || echo "background_guard: not installed or verify warning"
    command -v sentinelos-official-icon-baseline >/dev/null 2>&1 && sentinelos-official-icon-baseline --verify || echo "official_icon_baseline: not installed or verify warning"
    echo
    echo "== Appearance request =="
    echo "appearance_requested: $appearance"
    echo "root_user_theme_apply: no"
    echo "note: user-level theme apply remains controlled by sentinelos-theme-base."
    echo
    echo "conversion: complete"
    echo "note: converter mode did not wipe disks."
    echo "note: per-user MATE theme/background was not modified by root conversion."
  } | tee "$log"

  cp "$log" "$report_file"
  echo "conversion_log: $log"
  echo "conversion_report: $report_file"
}

case "${1:-}" in
  --summary) summary ;;
  --preflight) preflight ;;
  --plan) plan ;;
  --verify) verify ;;
  --report) report ;;
  --run) shift; run_conversion "$@" ;;
  --help|-h|"") usage ;;
  *) usage; exit 2 ;;
esac
