#!/usr/bin/env bash
# setup.sh - Deploy the Sovereign Orchestrator service
# This script installs all dependencies and configures the service
# to run on a Debian-based LXC container on the production Proxmox host.
#
# Usage: bash setup.sh
#
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
APP_DIR="/opt/sovereign-orchestrator"
SERVICE_NAME="sovereign-orchestrator"
SERVICE_USER="sovereign"
PORT=8888

echo "╔══════════════════════════════════════════════╗"
echo "║  Sovereign Orchestrator - Setup Script       ║"
echo "║  Theta42 Infrastructure Automation           ║"
echo "╚══════════════════════════════════════════════╝"
echo ""

# --- 1. System Dependencies ---
echo "[1/6] Installing system dependencies..."
apt-get update -qq
apt-get install -y -qq \
    python3 \
    python3-pip \
    python3-venv \
    xorriso \
    curl \
    jq \
    wget \
    2>/dev/null

# --- 2. Install proxmox-auto-install-assistant ---
echo "[2/6] Checking for proxmox-auto-install-assistant..."
if ! command -v proxmox-auto-install-assistant &>/dev/null; then
    echo "  -> Installing proxmox-auto-install-assistant from Proxmox repos..."
    # Add Proxmox repository for the assistant tool
    if [ ! -f /etc/apt/sources.list.d/proxmox.list ]; then
        CODENAME=$(grep VERSION_CODENAME /etc/os-release | cut -d= -f2 | tr -d '"')
        if [ -z "$CODENAME" ]; then
            CODENAME="bookworm"
        fi
        echo "deb [arch=amd64] http://download.proxmox.com/debian/pve $CODENAME pve-no-subscription" \
            > /etc/apt/sources.list.d/proxmox.list
        wget -qO "/etc/apt/trusted.gpg.d/proxmox-release-$CODENAME.gpg" \
            "http://download.proxmox.com/debian/proxmox-release-$CODENAME.gpg" 2>/dev/null || true
        apt-get update -qq
    fi
    apt-get install -y -qq proxmox-auto-install-assistant 2>/dev/null || {
        echo "  [!] Could not install from repo. Checking if binary exists locally..."
        if [ -f /usr/bin/proxmox-auto-install-assistant ]; then
            echo "  -> Found at /usr/bin/proxmox-auto-install-assistant"
        else
            echo "  [WARNING] proxmox-auto-install-assistant not available."
            echo "  ISO generation will fail until this is installed."
        fi
    }
else
    echo "  -> Already installed: $(which proxmox-auto-install-assistant)"
fi

# --- 3. Create service user ---
echo "[3/6] Setting up service user..."
if ! id "$SERVICE_USER" &>/dev/null; then
    useradd --system --home-dir "$APP_DIR" --shell /usr/sbin/nologin "$SERVICE_USER"
    echo "  -> Created user: $SERVICE_USER"
else
    echo "  -> User already exists: $SERVICE_USER"
fi

# --- 4. Install application ---
echo "[4/6] Installing application to $APP_DIR..."
mkdir -p "$APP_DIR"
cp -r "$SCRIPT_DIR/app" "$APP_DIR/"
cp -r "$SCRIPT_DIR/static" "$APP_DIR/"
cp "$SCRIPT_DIR/requirements.txt" "$APP_DIR/"

# Create Python virtual environment
python3 -m venv "$APP_DIR/venv"
"$APP_DIR/venv/bin/pip" install --quiet --upgrade pip
"$APP_DIR/venv/bin/pip" install --quiet -r "$APP_DIR/requirements.txt"

# Create data directories
mkdir -p "$APP_DIR/data/isos"
mkdir -p "$APP_DIR/data/builds"
mkdir -p "$APP_DIR/data/logs"

chown -R "$SERVICE_USER:$SERVICE_USER" "$APP_DIR"
echo "  -> Application installed successfully"

# --- 5. Configure Proxmox credentials ---
echo "[5/6] Configuring Proxmox credentials..."
CRED_FILE="$APP_DIR/.proxmox-credentials"
if [ -f "$HOME/.proxmox-credentials" ]; then
    cp "$HOME/.proxmox-credentials" "$CRED_FILE"
    chown "$SERVICE_USER:$SERVICE_USER" "$CRED_FILE"
    chmod 600 "$CRED_FILE"
    echo "  -> Credentials copied from $HOME/.proxmox-credentials"
elif [ -f /root/.proxmox-credentials ]; then
    cp /root/.proxmox-credentials "$CRED_FILE"
    chown "$SERVICE_USER:$SERVICE_USER" "$CRED_FILE"
    chmod 600 "$CRED_FILE"
    echo "  -> Credentials copied from /root/.proxmox-credentials"
else
    echo "  [WARNING] No Proxmox credentials found."
    echo "  Create $CRED_FILE with:"
    echo "    PROXMOX_HOST=https://your-pve-host:8006"
    echo "    PROXMOX_TOKEN_ID=user@pam!tokenname"
    echo "    PROXMOX_TOKEN_SECRET=your-token-secret"
fi

# --- 6. Create systemd service ---
echo "[6/6] Creating systemd service..."
cat > /etc/systemd/system/${SERVICE_NAME}.service << EOF
[Unit]
Description=Sovereign Orchestrator - Theta42 Infrastructure Automation
After=network.target
Wants=network-online.target

[Service]
Type=simple
User=${SERVICE_USER}
Group=${SERVICE_USER}
WorkingDirectory=${APP_DIR}
EnvironmentFile=-${CRED_FILE}
ExecStart=${APP_DIR}/venv/bin/uvicorn app.main:app --host 0.0.0.0 --port ${PORT}
Restart=on-failure
RestartSec=5
StandardOutput=append:${APP_DIR}/data/logs/service.log
StandardError=append:${APP_DIR}/data/logs/service-error.log

# Security hardening
NoNewPrivileges=true
ProtectSystem=strict
ReadWritePaths=${APP_DIR}/data
ProtectHome=true

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable ${SERVICE_NAME}
echo "  -> Service created and enabled"

echo ""
echo "╔══════════════════════════════════════════════╗"
echo "║  Setup Complete!                             ║"
echo "╚══════════════════════════════════════════════╝"
echo ""
echo "  Start the service:  systemctl start ${SERVICE_NAME}"
echo "  Check status:       systemctl status ${SERVICE_NAME}"
echo "  View logs:          journalctl -u ${SERVICE_NAME} -f"
echo "  Web UI:             http://$(hostname -I | awk '{print $1}'):${PORT}"
echo ""
