#!/bin/bash
# Chromium kiosk launcher for MageDok 7" display via Cage Wayland compositor
# Lightweight fullscreen web app display (SaltyFace web UI)
# Replaces GNOME desktop environment (~650MB RAM savings)
#
# Usage:
#   chromium_kiosk.sh [--url URL] [--debug]
#
# Environment:
#   SALTYBOT_KIOSK_URL     Default URL if not specified (localhost:3000)
#   DISPLAY                Not used (Wayland native)
#   XDG_RUNTIME_DIR        Must be set for Wayland

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LOG_FILE="${SCRIPT_DIR}/../../logs/chromium_kiosk.log"
mkdir -p "$(dirname "$LOG_FILE")"

# Logging
log() {
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" | tee -a "$LOG_FILE"
}

# Configuration
KIOSK_URL="${SALTYBOT_KIOSK_URL:-http://localhost:3000}"
DEBUG_MODE=false
CAGE_CONFIG="/opt/saltybot/config/cage-magedok.ini"

# Parse arguments
while [[ $# -gt 0 ]]; do
  case $1 in
    --url)
      KIOSK_URL="$2"
      shift 2
      ;;
    --debug)
      DEBUG_MODE=true
      shift
      ;;
    *)
      log "Unknown option: $1"
      exit 1
      ;;
  esac
done

# Setup environment
export WAYLAND_DISPLAY=wayland-0
export XDG_RUNTIME_DIR=/run/user/$(id -u)
export XDG_SESSION_TYPE=wayland
export QT_QPA_PLATFORM=wayland

# Ensure Wayland runtime directory exists
mkdir -p "$XDG_RUNTIME_DIR"
chmod 700 "$XDG_RUNTIME_DIR"

log "Starting Chromium kiosk on Cage Wayland compositor"
log "URL: $KIOSK_URL"

# Chromium kiosk flags
CHROMIUM_FLAGS=(
  --kiosk                           # Fullscreen kiosk mode (no UI chrome)
  --disable-session-crashed-bubble # No crash recovery UI
  --disable-infobars               # No info bars
  --no-first-run                   # Skip first-run wizard
  --no-default-browser-check       # Skip browser check
  --disable-sync                   # Disable Google Sync
  --disable-translate              # Disable translate prompts
  --disable-plugins-power-saver    # Don't power-save plugins
  --autoplay-policy=user-gesture-required
  --app="$KIOSK_URL"               # Run as web app in fullscreen
)

# Optional debug flags
if $DEBUG_MODE; then
  CHROMIUM_FLAGS+=(
    --enable-logging=stderr
    --log-level=0
  )
fi

# Launch Cage with Chromium as client
log "Launching Cage with Chromium..."
if [ -f "$CAGE_CONFIG" ]; then
  log "Using Cage config: $CAGE_CONFIG"
  exec cage -s chromium "${CHROMIUM_FLAGS[@]}" 2>&1 | tee -a "$LOG_FILE"
else
  log "Cage config not found, using defaults: $CAGE_CONFIG"
  exec cage -s chromium "${CHROMIUM_FLAGS[@]}" 2>&1 | tee -a "$LOG_FILE"
fi
