#!/bin/bash
# Control Center Kiosk Startup Script
# ====================================
# This script launches Chromium in kiosk mode for the Control Center dashboard
# Usage: ./start-kiosk.sh [frontend-url]

set -e

FRONTEND_URL="${1:-http://localhost:3000}"
BROWSER_WINDOW="chromium-browser"

# ── Functions ────────────────────────────────────────────────────────────

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*"
}

cleanup() {
    log "Stopping kiosk browser..."
    pkill -f "chromium-browser.*--kiosk" || true
}

trap cleanup SIGINT SIGTERM

# ── Check prerequisites ──────────────────────────────────────────────────

check_browser() {
    if ! command -v chromium-browser &> /dev/null; then
        log "ERROR: chromium-browser not found"
        log "Install with: sudo apt-get install chromium"
        exit 1
    fi
}

check_x_server() {
    if [ -z "$DISPLAY" ]; then
        log "ERROR: DISPLAY environment variable not set"
        log "This script requires an X server session"
        exit 1
    fi
}

# ── Main ────────────────────────────────────────────────────────────────

main() {
    log "Starting Control Center Kiosk..."
    log "Frontend URL: $FRONTEND_URL"
    
    check_browser
    check_x_server
    
    # Clean up any existing browser instances
    cleanup
    
    # Launch Chromium in kiosk mode
    # --kiosk: Fullscreen without browser UI
    # --incognito: Clean session
    # --noerrdialogs: Suppress error dialogs
    # --disable-notifications: Disable notifications
    # --disable-extensions: Disable extensions
    # --disable-plugins-discovery: Disable plugins
    # --disable-sync: Disable sync
    # --disable-web-security: Allow CORS (needed for local API calls)
    # --ignore-certificate-errors: Ignore SSL errors (for local dev)
    # --gpu: Enable GPU acceleration
    # --start-fullscreen: Start in fullscreen mode
    chromium-browser \
        --kiosk \
        --incognito \
        --noerrdialogs \
        --disable-notifications \
        --disable-extensions \
        --disable-plugins-discovery \
        --disable-sync \
        --disable-web-security \
        --ignore-certificate-errors \
        --gpu \
        --start-fullscreen \
        "$FRONTEND_URL" &
    
    KIOSK_PID=$!
    log "Kiosk browser started (PID: $KIOSK_PID)"
    
    # Wait for browser to exit
    wait $KIOSK_PID
}

main "$@"
