#!/usr/bin/env bash
# ============================================================
#  Auto-Presentee — Termux / Android Quick Installer
#  Run: bash <(curl -s https://apt.nofails.qzz.io)
# ============================================================
set -euo pipefail

INSTALL_DIR="/sdcard/autopresentee"
REPO_URL="https://git.nofails.qzz.io/svteam/auto_presentee/raw/branch/main"
PORT="${PORT:-8080}"
GREEN='\033[0;32m'
CYAN='\033[0;36m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo -e "${CYAN}"
echo "  ╔═══════════════════════════════════════════════╗"
echo "  ║   🎓 Auto-Presentee — Termux Installer       ║"
echo "  ╚═══════════════════════════════════════════════╝"
echo -e "${NC}"

# --- Check we're in Termux ---
if [ ! -d "/data/data/com.termux" ] && [ ! -d "/data/user/0/com.termux" ]; then
    echo -e "${RED}✗ This script is designed for Termux.${NC}"
    echo -e "  Install Termux from F-Droid: https://f-droid.org/en/packages/com.termux/"
    echo ""
    echo -e "  If you're on Linux, use: ${CYAN}bash <(curl -s https://apl.nofails.qzz.io)${NC}"
    exit 1
fi

echo -e "${GREEN}✓${NC} Running in Termux"

# --- Install dependencies ---
echo -e "${CYAN}[1/6]${NC} Installing dependencies..."

pkg update -y -qq 2>/dev/null || true
pkg install -y python curl 2>/dev/null || true

PYTHON=$(command -v python3 || command -v python)
echo -e "${GREEN}✓${NC} Python: $($PYTHON --version 2>&1)"
echo -e "${GREEN}✓${NC} curl found"

# --- Create install directory ---
echo -e "${CYAN}[2/6]${NC} Setting up installation directory..."
mkdir -p "$INSTALL_DIR"

# --- Download app files ---
echo -e "${CYAN}[3/6]${NC} Downloading Auto-Presentee files..."
cd "$INSTALL_DIR"

FILES=("index.html" "style.css" "script.js" "index_offline.html")
for file in "${FILES[@]}"; do
    if curl -sSf -o "$file" "$REPO_URL/$file" 2>/dev/null; then
        echo -e "  ${GREEN}✓${NC} $file"
    else
        echo -e "  ${RED}✗${NC} Failed to download $file"
    fi
done

# Download offline model installer
if curl -sSf -o "download_models.sh" "$REPO_URL/download_models.sh" 2>/dev/null; then
    chmod +x download_models.sh
    echo -e "  ${GREEN}✓${NC} download_models.sh"
fi

echo -e "${GREEN}✓${NC} Files downloaded to $INSTALL_DIR"

# --- Download face-api models ---
echo -e "${CYAN}[4/6]${NC} Downloading face recognition models (~6MB)..."
if [ ! -d "models" ]; then
    if [ -f "download_models.sh" ]; then
        bash download_models.sh
        echo -e "${GREEN}✓${NC} Models downloaded"
    else
        echo -e "  Downloading models manually..."
        mkdir -p models
        MODEL_BASE="https://cdn.jsdelivr.net/npm/@vladmandic/face-api/model"
        for model in tiny_face_detector_model-weights_manifest.json tiny_face_detector_model-shard1 tiny_face_detector_model-shard2 face_landmark_68_model-weights_manifest.json face_landmark_68_model-shard1 face_recognition_model-weights_manifest.json face_recognition_model-shard1 face_recognition_model-shard2; do
            curl -sSf -o "models/$model" "$MODEL_BASE/$model" 2>/dev/null && echo -e "  ${GREEN}✓${NC} $model" || true
        done
    fi
else
    echo -e "${GREEN}✓${NC} Models already present"
fi

# --- Create start script ---
echo -e "${CYAN}[5/6]${NC} Creating start script..."
cat > "$INSTALL_DIR/start.sh" << 'STARTEOF'
#!/data/data/com.termux/files/usr/bin/bash
cd "$(dirname "$0")"
PORT="${PORT:-8080}"
PYTHON=$(command -v python3 || command -v python)

echo "🎓 Auto-Presentee starting on http://localhost:$PORT"
echo "   Open this URL in Chrome on this device."
echo "   Press Ctrl+C to stop."
echo ""

$PYTHON -m http.server "$PORT"
STARTEOF
chmod +x "$INSTALL_DIR/start.sh"

# --- Create Termux:Boot auto-start script ---
echo -e "${CYAN}[6/6]${NC} Setting up auto-start on boot..."

BOOT_DIR="$HOME/.termux/boot"
mkdir -p "$BOOT_DIR"

cat > "$BOOT_DIR/start-autopresentee.sh" << 'BOOTEOF'
#!/data/data/com.termux/files/usr/bin/bash
termux-wake-lock
cd /sdcard/autopresentee
PYTHON=$(command -v python3 || command -v python)
$PYTHON -m http.server 8080 &
BOOTEOF
chmod +x "$BOOT_DIR/start-autopresentee.sh"

echo -e "${GREEN}✓${NC} Auto-start script created at $BOOT_DIR/start-autopresentee.sh"

# --- Check for Termux:Boot ---
if pm list packages 2>/dev/null | grep -q "com.termux.boot"; then
    echo -e "${GREEN}✓${NC} Termux:Boot detected — auto-start is active"
else
    echo -e "${YELLOW}⚠${NC} Termux:Boot not installed"
    echo -e "  For auto-start on boot, install Termux:Boot from F-Droid"
    echo -e "  Then reboot or re-run this script"
fi

# --- Check for Fully Kiosk Browser ---
echo ""
echo -e "${CYAN}📱 Kiosk Mode Setup (Recommended):${NC}"
echo -e "  1. Install ${YELLOW}Fully Kiosk Browser${NC} from Play Store"
echo -e "  2. Set start URL to: ${CYAN}http://localhost:$PORT${NC}"
echo -e "  3. Enable 'Start on boot' in Fully Kiosk settings"
echo -e "  4. The board will auto-launch into attendance mode on power-on"
echo ""

# --- Done ---
echo ""
echo -e "${GREEN}╔═════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║   🎓 Auto-Presentee installed successfully!    ║${NC}"
echo -e "${GREEN}╚═════════════════════════════════════════════════╝${NC}"
echo ""
echo -e "  Install location: ${CYAN}$INSTALL_DIR${NC}"
echo -e "  Start command:    ${CYAN}cd $INSTALL_DIR && bash start.sh${NC}"
echo -e "  Or manually:      ${CYAN}cd $INSTALL_DIR && $PYTHON -m http.server $PORT${NC}"
echo -e "  Open in Chrome:   ${CYAN}http://localhost:$PORT${NC}"
echo ""
echo -e "  Auto-start:       Boot script installed (needs Termux:Boot)"
echo -e "  Kiosk mode:       Use Fully Kiosk Browser"
echo ""
echo -e "  To update later, run this script again."
echo ""
