#!/usr/bin/env bash
# ============================================
# GoVista Player — Linux Kiosk Setup Script
# ============================================
# Configures a Linux machine for unattended
# digital signage operation with GoVista Player.
#
# Usage: sudo bash linux-kiosk-setup.sh [--autologin]
#
# What this script does:
#   1. Downloads the latest AppImage from Supabase
#   2. Installs it to /opt/govision/
#   3. Creates a systemd user service with watchdog
#   4. Disables screen blanking and DPMS
#   5. Optionally configures autologin
#   6. Enables and starts the service

set -euo pipefail

# --- Configuration ---
INSTALL_DIR="/opt/govision"
APPIMAGE_URL="https://vjllztzjsjnmdxzwnaxw.supabase.co/storage/v1/object/public/releases/linux/GoVista-Player-1.5.58.AppImage"
APPIMAGE_NAME="GoVista-Player.AppImage"
SERVICE_NAME="govision-player"
AUTOLOGIN=false

# Parse arguments
for arg in "$@"; do
  case "$arg" in
    --autologin) AUTOLOGIN=true ;;
    --help|-h)
      echo "Usage: sudo bash linux-kiosk-setup.sh [--autologin]"
      echo ""
      echo "Options:"
      echo "  --autologin    Configure automatic login for the current user"
      echo "  --help, -h     Show this help message"
      exit 0
      ;;
  esac
done

# Determine the actual user (even when running via sudo)
REAL_USER="${SUDO_USER:-$USER}"
REAL_HOME=$(eval echo "~${REAL_USER}")

echo "========================================"
echo " GoVista Player — Linux Kiosk Setup"
echo "========================================"
echo ""
echo "User:        ${REAL_USER}"
echo "Install dir: ${INSTALL_DIR}"
echo "Autologin:   ${AUTOLOGIN}"
echo ""

# --- Step 1: Download AppImage ---
echo "[1/6] Downloading GoVista Player AppImage..."
mkdir -p "${INSTALL_DIR}"

if command -v wget &>/dev/null; then
  wget -q --show-progress -O "${INSTALL_DIR}/${APPIMAGE_NAME}" "${APPIMAGE_URL}"
elif command -v curl &>/dev/null; then
  curl -L --progress-bar -o "${INSTALL_DIR}/${APPIMAGE_NAME}" "${APPIMAGE_URL}"
else
  echo "ERROR: Neither wget nor curl found. Please install one and retry."
  exit 1
fi

echo "  Downloaded to ${INSTALL_DIR}/${APPIMAGE_NAME}"

# --- Step 2: Make executable ---
echo "[2/6] Setting permissions..."
chmod +x "${INSTALL_DIR}/${APPIMAGE_NAME}"
chown "${REAL_USER}:${REAL_USER}" "${INSTALL_DIR}/${APPIMAGE_NAME}"
echo "  AppImage is now executable"

# --- Step 3: Create systemd user service ---
echo "[3/6] Creating systemd service..."
SERVICE_DIR="${REAL_HOME}/.config/systemd/user"
mkdir -p "${SERVICE_DIR}"

cat > "${SERVICE_DIR}/${SERVICE_NAME}.service" <<EOF
[Unit]
Description=GoVista Digital Signage Player
After=graphical-session.target
Wants=graphical-session.target

[Service]
Type=simple
ExecStart=${INSTALL_DIR}/${APPIMAGE_NAME} --no-sandbox
Restart=always
RestartSec=5
Environment=DISPLAY=:0
Environment=XAUTHORITY=${REAL_HOME}/.Xauthority
WatchdogSec=120

[Install]
WantedBy=default.target
EOF

chown -R "${REAL_USER}:${REAL_USER}" "${SERVICE_DIR}"
echo "  Service file created at ${SERVICE_DIR}/${SERVICE_NAME}.service"

# --- Step 4: Disable screen blanking ---
echo "[4/6] Disabling screen blanking and DPMS..."

# Create an autostart entry to disable screen blanking on login
AUTOSTART_DIR="${REAL_HOME}/.config/autostart"
mkdir -p "${AUTOSTART_DIR}"

cat > "${AUTOSTART_DIR}/disable-screensaver.desktop" <<EOF
[Desktop Entry]
Type=Application
Name=Disable Screensaver
Exec=sh -c 'xset s off; xset -dpms; xset s noblank'
X-GNOME-Autostart-enabled=true
Terminal=false
Comment=Disable screen blanking for kiosk mode
EOF

chown -R "${REAL_USER}:${REAL_USER}" "${AUTOSTART_DIR}"
echo "  Screen blanking will be disabled on next login"

# --- Step 5: Configure autologin (optional) ---
if [ "${AUTOLOGIN}" = true ]; then
  echo "[5/6] Configuring autologin for ${REAL_USER}..."

  # GDM (GNOME)
  if [ -f /etc/gdm3/custom.conf ]; then
    sed -i "s/^#\?AutomaticLoginEnable=.*/AutomaticLoginEnable=true/" /etc/gdm3/custom.conf
    sed -i "s/^#\?AutomaticLogin=.*/AutomaticLogin=${REAL_USER}/" /etc/gdm3/custom.conf
    echo "  GDM autologin configured"
  # LightDM
  elif [ -f /etc/lightdm/lightdm.conf ]; then
    sed -i "s/^#\?autologin-user=.*/autologin-user=${REAL_USER}/" /etc/lightdm/lightdm.conf
    echo "  LightDM autologin configured"
  # LightDM (Raspberry Pi)
  elif [ -d /etc/lightdm/lightdm.conf.d ]; then
    cat > /etc/lightdm/lightdm.conf.d/50-govision-autologin.conf <<INNER
[Seat:*]
autologin-user=${REAL_USER}
autologin-user-timeout=0
INNER
    echo "  LightDM autologin configured (Raspberry Pi)"
  else
    echo "  WARNING: Could not detect display manager. Please configure autologin manually."
  fi
else
  echo "[5/6] Skipping autologin (use --autologin to enable)"
fi

# --- Step 6: Enable and start the service ---
echo "[6/6] Enabling and starting GoVista Player service..."

# Enable lingering so user services start at boot
loginctl enable-linger "${REAL_USER}"

# Enable the service as the real user
su - "${REAL_USER}" -c "XDG_RUNTIME_DIR=/run/user/$(id -u ${REAL_USER}) systemctl --user daemon-reload"
su - "${REAL_USER}" -c "XDG_RUNTIME_DIR=/run/user/$(id -u ${REAL_USER}) systemctl --user enable ${SERVICE_NAME}.service"
su - "${REAL_USER}" -c "XDG_RUNTIME_DIR=/run/user/$(id -u ${REAL_USER}) systemctl --user start ${SERVICE_NAME}.service" 2>/dev/null || true

echo ""
echo "========================================"
echo " Setup Complete!"
echo "========================================"
echo ""
echo "GoVista Player is now installed and configured."
echo ""
echo "The player will:"
echo "  - Start automatically on boot"
echo "  - Restart automatically if it crashes"
echo "  - Keep the screen on (no blanking/DPMS)"
echo ""
echo "Next steps:"
echo "  1. A pairing code will appear on screen"
echo "  2. Go to your GoVista Dashboard"
echo "  3. Add a new device and enter the pairing code"
echo ""
echo "Useful commands:"
echo "  Status:  systemctl --user status ${SERVICE_NAME}"
echo "  Logs:    journalctl --user -u ${SERVICE_NAME} -f"
echo "  Stop:    systemctl --user stop ${SERVICE_NAME}"
echo "  Restart: systemctl --user restart ${SERVICE_NAME}"
echo ""
