#!/bin/bash

###############################################################################
# Liveposter Raspberry Pi Kiosk Setup Script
# Configures a Raspberry Pi to run as a fullscreen kiosk display
# Tested on: Raspberry Pi 5 with Raspberry Pi OS (64-bit)
###############################################################################

set -e  # Exit on any error

echo "=================================================="
echo "  Liveposter Kiosk Setup for Raspberry Pi"
echo "=================================================="
echo ""
echo "This script will:"
echo "  ✓ Install Chromium browser with GPU acceleration"
echo "  ✓ Configure 4K@60Hz HDMI output"
echo "  ✓ Setup auto-boot to fullscreen kiosk mode"
echo "  ✓ Hide cursor and UI elements"
echo "  ✓ Disable screen blanking"
echo "  ✓ Optimize for smooth animations"
echo ""
read -p "Continue? (y/n) " -n 1 -r
echo ""
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Setup cancelled."
    exit 1
fi

###############################################################################
# 1. Update System
###############################################################################
echo ""
echo "Step 1/7: Updating system packages..."
sudo apt-get update
sudo apt-get upgrade -y

###############################################################################
# 2. Install Dependencies
###############################################################################
echo ""
echo "Step 2/7: Installing Chromium and dependencies..."
sudo apt-get install -y \
    chromium-browser \
    xdotool \
    unclutter \
    sed \
    x11-xserver-utils

###############################################################################
# 3. Configure HDMI Output for 4K@60Hz
###############################################################################
echo ""
echo "Step 3/7: Configuring HDMI for 4K@60Hz..."

# Backup existing config
sudo cp /boot/firmware/config.txt /boot/firmware/config.txt.backup

# Check if config already exists
if grep -q "# Liveposter Kiosk Configuration" /boot/firmware/config.txt; then
    echo "⚠️  Kiosk configuration already exists in config.txt, skipping..."
else
    # Add kiosk configuration
    sudo tee -a /boot/firmware/config.txt > /dev/null <<EOF

# Liveposter Kiosk Configuration
# 4K@60Hz HDMI output
hdmi_group=2
hdmi_mode=87
hdmi_cvt=3840 2160 60 3 0 0 0
hdmi_drive=2
max_framebuffer_width=3840
max_framebuffer_height=2160

# GPU Memory (important for smooth rendering)
gpu_mem=256

# Disable screen blanking
hdmi_blanking=1
EOF
    echo "✓ HDMI configuration added to /boot/firmware/config.txt"
fi

###############################################################################
# 4. Create Kiosk Directory
###############################################################################
echo ""
echo "Step 4/7: Creating kiosk directory..."
mkdir -p /home/$USER/kiosk
echo "✓ Created /home/$USER/kiosk/"

###############################################################################
# 5. Create Autostart Script
###############################################################################
echo ""
echo "Step 5/7: Setting up autostart script..."

# Create autostart directory if it doesn't exist
mkdir -p /home/$USER/.config/lxsession/LXDE-pi

# Create autostart file
cat > /home/$USER/.config/lxsession/LXDE-pi/autostart <<EOF
# Disable screen blanking
@xset s off
@xset s noblank
@xset -dpms

# Hide mouse cursor
@unclutter -idle 0.1 -root

# Launch Chromium in kiosk mode
@chromium-browser \\
    --kiosk \\
    --noerrdialogs \\
    --disable-infobars \\
    --disable-session-crashed-bubble \\
    --disable-translate \\
    --disable-save-password-bubble \\
    --disable-features=TranslateUI \\
    --disable-component-update \\
    --no-first-run \\
    --fast \\
    --fast-start \\
    --disable-features=TouchpadOverscrollHistoryNavigation \\
    --overscroll-history-navigation=0 \\
    --enable-features=VaapiVideoDecoder \\
    --use-gl=egl \\
    --enable-accelerated-video-decode \\
    --enable-gpu-rasterization \\
    --enable-zero-copy \\
    --ignore-gpu-blocklist \\
    --disk-cache-size=104857600 \\
    file:///home/$USER/kiosk/index.html
EOF

echo "✓ Created autostart script"

###############################################################################
# 6. Configure Auto-Login
###############################################################################
echo ""
echo "Step 6/7: Configuring auto-login..."

# Backup existing autologin config
sudo cp /etc/lightdm/lightdm.conf /etc/lightdm/lightdm.conf.backup 2>/dev/null || true

# Create/update lightdm config for auto-login
sudo tee /etc/lightdm/lightdm.conf > /dev/null <<EOF
[Seat:*]
autologin-user=$USER
autologin-user-timeout=0
user-session=LXDE-pi
EOF

echo "✓ Auto-login configured for user: $USER"

###############################################################################
# 7. Verify Liveposter Content
###############################################################################
echo ""
echo "Step 7/7: Verifying Liveposter content..."

# Check if index.html exists
if [ -f /home/$USER/kiosk/index.html ]; then
    echo "✓ Found index.html - Liveposter content is ready"
else
    echo ""
    echo "⚠️  WARNING: index.html not found in /home/$USER/kiosk/"
    echo ""
    echo "It looks like you haven't transferred your Liveposter content yet."
    echo ""
    echo "To build and deploy your content:"
    echo "  1. On your development computer:"
    echo "     npx liveposter buildpi your-poster-list.json"
    echo ""
    echo "  2. Transfer the dist-pi folder contents to this Pi:"
    echo "     scp -r dist-pi/* pi@$(hostname -I | awk '{print $1}'):/home/$USER/kiosk/"
    echo ""
    echo "  3. Then reboot: sudo reboot"
    echo ""
fi

###############################################################################
# 8. Final Instructions
###############################################################################
echo ""
echo "=================================================="
echo "  ✓ Kiosk Setup Complete!"
echo "=================================================="
echo ""

# Check if content is ready
if [ -f /home/$USER/kiosk/index.html ]; then
    echo "Your Raspberry Pi is configured and ready!"
    echo ""
    echo "🎉 To start kiosk mode, simply reboot:"
    echo "   sudo reboot"
    echo ""
    echo "After reboot, your Pi will boot directly into fullscreen"
    echo "kiosk mode displaying your Liveposter content."
else
    echo "Setup is complete, but you still need to add your content."
    echo ""
    echo "Next steps:"
    echo "  1. Transfer your dist-pi content to /home/$USER/kiosk/"
    echo "  2. Reboot: sudo reboot"
fi

echo ""
echo "Configuration files created:"
echo "  • /home/$USER/.config/lxsession/LXDE-pi/autostart"
echo "  • /etc/lightdm/lightdm.conf"
echo "  • /boot/firmware/config.txt (4K@60Hz settings)"
echo ""
echo "Backups saved:"
echo "  • /etc/lightdm/lightdm.conf.backup"
echo "  • /boot/firmware/config.txt.backup"
echo ""
echo "To disable kiosk mode, delete the autostart file:"
echo "  rm /home/$USER/.config/lxsession/LXDE-pi/autostart"
echo ""
echo "To update your content:"
echo "  1. Build new content: npx liveposter buildpi updated.json"
echo "  2. Transfer: scp -r dist-pi/* pi@$(hostname -I | awk '{print $1}'):/home/$USER/kiosk/"
echo "  3. Refresh: ssh pi@$(hostname -I | awk '{print $1}') \"DISPLAY=:0 xdotool key F5\""
echo ""
echo "=================================================="
