#!/bin/bash
# ==============================================================================
# AETHER-7: Raspberry Pi 5 + 7-inch Display Kiosk Setup Script
# Automates full-screen Chromium kiosk mode and telemetry service on Pi OS Bookworm
# ==============================================================================

set -e

echo "=========================================================="
echo "🚀 AETHER-7: Setting up 7\" Kiosk on Raspberry Pi 5"
echo "=========================================================="

HUB_URL="${1:-http://MacBook-Pro.local:4040}"

echo "Target Hub Server URL: $HUB_URL"
echo ""

# 1. Update package lists and install required tools
echo "[1/4] Installing necessary kiosk packages..."
sudo apt-get update -y
sudo apt-get install -y unclutter python3 curl
# the browser package is called chromium-browser on Bookworm and chromium on newer Pi OS: install whichever this release has
sudo apt-get install -y chromium-browser || sudo apt-get install -y chromium

# 2. Setup Udev Rule for Hardware Backlight Dimming (Prevents LCD/OLED Burn-in)
echo "[2/4] Setting up hardware display backlight permissions..."
sudo tee /etc/udev/rules.d/99-backlight.rules > /dev/null <<EOF
SUBSYSTEM=="backlight", ACTION=="add", RUN+="/bin/chmod 666 /sys/class/backlight/%k/brightness /sys/class/backlight/%k/bl_power"
EOF
sudo udevadm control --reload-rules && sudo udevadm trigger || true

# 3. Setup Pi Telemetry Agent
echo "[3/4] Setting up background telemetry agent..."
AGENT_DIR="$HOME/aether-pi-agent"
mkdir -p "$AGENT_DIR"

if [ -f "collectors/pi_collector.py" ]; then
    cp collectors/pi_collector.py "$AGENT_DIR/pi_collector.py"
elif [ -f "pi_collector.py" ]; then
    cp pi_collector.py "$AGENT_DIR/pi_collector.py"
else
    # Fetch from Hub if local file not found
    echo "Downloading pi_collector.py from hub..."
    curl -sSL "$HUB_URL/pi_collector.py" -o "$AGENT_DIR/pi_collector.py" || true
fi

chmod +x "$AGENT_DIR/pi_collector.py"

# Create Systemd Service for Telemetry Agent
echo "      Registering aether-agent.service..."
sudo tee /etc/systemd/system/aether-agent.service > /dev/null <<EOF
[Unit]
Description=AETHER-7 Pi 5 Telemetry Agent
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=$USER
WorkingDirectory=$AGENT_DIR
ExecStart=/usr/bin/python3 $AGENT_DIR/pi_collector.py --hub $HUB_URL --interval 1.5
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

sudo systemctl daemon-reload
sudo systemctl enable aether-agent.service
sudo systemctl restart aether-agent.service
echo "✓ Telemetry agent service activated and running."

# 4. Configure Kiosk Autostart for 7" Touchscreen (Wayland & X11 compatible)
echo "[4/4] Configuring 7-inch full-screen kiosk autostart..."

KIOSK_LAUNCHER="$HOME/.local/bin/launch_kiosk.sh"
mkdir -p "$HOME/.local/bin"

cat > "$KIOSK_LAUNCHER" <<EOF
#!/bin/bash
# Wait for display and network
sleep 3
# Hide mouse cursor when idle
unclutter -idle 0.5 -root &

# Launch Chromium in Kiosk Mode for 7" Display (the browser is chromium-browser or chromium, depending on the Pi OS release)
BROWSER=\$(command -v chromium-browser || command -v chromium)
\$BROWSER \\
  --kiosk \\
  --noerrdialogs \\
  --disable-infobars \\
  --disable-session-crashed-bubble \\
  --disable-pinch \\
  --overscroll-history-navigation=0 \\
  --check-for-update-interval=31536000 \\
  "$HUB_URL"
EOF

chmod +x "$KIOSK_LAUNCHER"

# Wayland / Wayfire Autostart (Default in Pi OS Bookworm)
WAYFIRE_INI="$HOME/.config/wayfire.ini"
if [ -f "$WAYFIRE_INI" ]; then
    if ! grep -q "aether_kiosk" "$WAYFIRE_INI"; then
        echo -e "\n[autostart]\naether_kiosk = $KIOSK_LAUNCHER" >> "$WAYFIRE_INI"
    fi
fi

# Labwc Autostart (Pi OS Bookworm alternative)
LABWC_AUTOSTART="$HOME/.config/labwc/autostart"
mkdir -p "$HOME/.config/labwc"
if ! grep -q "launch_kiosk.sh" "$LABWC_AUTOSTART" 2>/dev/null; then
    echo "$KIOSK_LAUNCHER &" >> "$LABWC_AUTOSTART"
fi

# LXDE / X11 Autostart fallback
LXDE_AUTOSTART="$HOME/.config/lxsession/LXDE-pi/autostart"
mkdir -p "$HOME/.config/lxsession/LXDE-pi"
if ! grep -q "launch_kiosk.sh" "$LXDE_AUTOSTART" 2>/dev/null; then
    echo "@$KIOSK_LAUNCHER" >> "$LXDE_AUTOSTART"
fi

echo ""
echo "=========================================================="
echo "🎉 AETHER-7 Kiosk installation complete!"
echo "=========================================================="
echo "1. To test right now, run:"
echo "   $KIOSK_LAUNCHER"
echo ""
echo "2. On next reboot, your 7\" display will automatically"
echo "   launch directly into the AETHER-7 AI Monitor!"
echo "=========================================================="

