#!/bin/bash
#
# Setup Archipelago kiosk mode on the server
# Runs Chromium in kiosk mode so keyboard/touchpad control the web UI
# Only starts when logging in at the physical console (tty1)
#
# Run on server: sudo ./setup-kiosk.sh
#

set -e

KIOSK_USER="${1:-archipelago}"
ARCHIPELAGO_URL="${ARCHIPELAGO_URL:-http://localhost}"

echo "Setting up kiosk for user: $KIOSK_USER"
echo "URL: $ARCHIPELAGO_URL"
echo ""

# Create .xinitrc for kiosk
HOMEDIR=$(getent passwd "$KIOSK_USER" | cut -d: -f6)
XINITRC="$HOMEDIR/.xinitrc"

cat > "$XINITRC" << 'XINITRC_EOF'
#!/bin/bash
# Archipelago kiosk - Chromium fullscreen
exec chromium --kiosk \
  --app=http://localhost \
  --noerrdialogs \
  --disable-infobars \
  --disable-translate \
  --no-first-run \
  --check-for-update-interval=31536000 \
  --disable-features=TranslateUI \
  --disable-session-crashed-bubble
XINITRC_EOF

# Replace localhost with actual URL if different
if [ "$ARCHIPELAGO_URL" != "http://localhost" ]; then
  sed -i "s|http://localhost|$ARCHIPELAGO_URL|g" "$XINITRC"
fi

chown "$KIOSK_USER:$KIOSK_USER" "$XINITRC"
chmod +x "$XINITRC"

# Add startx to .bash_profile only when on console (tty1)
BASHPROFILE="$HOMEDIR/.bash_profile"
if [ ! -f "$BASHPROFILE" ]; then
  touch "$BASHPROFILE"
  chown "$KIOSK_USER:$KIOSK_USER" "$BASHPROFILE"
fi

# Remove any existing kiosk block
if grep -q "ARCHIPELAGO_KIOSK" "$BASHPROFILE" 2>/dev/null; then
  sed -i '/# ARCHIPELAGO_KIOSK/,/^# END ARCHIPELAGO_KIOSK/d' "$BASHPROFILE"
fi

# Add kiosk startup (only runs on physical console tty1)
cat >> "$BASHPROFILE" << 'BASHPROFILE_EOF'

# ARCHIPELAGO_KIOSK - Start X/kiosk when logging in at physical console
if [ -z "$DISPLAY" ] && [ "$(tty)" = "/dev/tty1" ]; then
  exec startx
fi
# END ARCHIPELAGO_KIOSK
BASHPROFILE_EOF

chown "$KIOSK_USER:$KIOSK_USER" "$BASHPROFILE"

echo "✅ Kiosk installed!"
echo ""
echo "  When you log in at the physical console (monitor + keyboard):"
echo "  - X will start automatically"
echo "  - Chromium will open in kiosk mode"
echo "  - Your keyboard/touchpad will control the Archipelago UI"
echo ""
echo "  To use: Connect a display, plug in keyboard, reboot (or log in at tty1)"
echo ""
