#!/bin/bash

# Raspberry Pi Zero Kiosk Setup Script
# Run this on a fresh Raspberry Pi OS Lite installation or to update existing setup

set -e  # Exit on any error

echo "🚀 Setting up Raspberry Pi Zero as React App Kiosk..."

# Configuration - Edit these variables
GITHUB_REPO_URL="https://github.com/tomhillmeyer/companion-dashboard"  # Your GitHub repo URL
DIST_FOLDER_PATH="dist"  # Path to dist folder in your repo
APP_NAME="companion-dashboard"

# Update system
echo "📦 Updating system packages..."
sudo apt update && sudo apt upgrade -y

# Install required packages (including X11 dependencies)
echo "📦 Installing required packages..."
sudo apt install -y \
    nginx \
    xserver-xorg \
    xserver-xorg-video-fbdev \
    xserver-xorg-input-evdev \
    xserver-xorg-legacy \
    xinit \
    openbox \
    git \
    unclutter \
    curl \
    firefox-esr \
    matchbox-window-manager \
    xserver-xorg-input-libinput \
    adwaita-icon-theme
    

# Check Pi model and install appropriate browser
PI_MODEL=$(cat /proc/cpuinfo | grep "Revision" | cut -d: -f2 | tr -d ' ')
echo "🔍 Detected Pi revision: $PI_MODEL"

# Pi Zero 1st gen has ARMv6 - Chromium won't work, use Firefox ESR
if [[ "$PI_MODEL" =~ ^(900092|900093|920092|920093)$ ]]; then
    echo "⚠️  Pi Zero 1st gen detected - Chromium not supported, using Firefox ESR"
    BROWSER_CMD="firefox-esr"
    BROWSER_ARGS="--kiosk --private-window"
else
    echo "✅ Pi supports Chromium"
    sudo apt install -y chromium-browser
    BROWSER_CMD="chromium-browser"
    BROWSER_ARGS="--no-sandbox --disable-dev-shm-usage --disable-gpu --no-first-run --disable-infobars --disable-session-crashed-bubble --disable-suggestions-ui --disable-translate --disable-web-security --disable-features=VizDisplayCompositor --disable-ipc-flooding-protection --disable-background-timer-throttling --disable-backgrounding-occluded-windows --disable-renderer-backgrounding --kiosk --incognito --autoplay-policy=no-user-gesture-required"
fi

# Clean up any existing broken services
echo "🧹 Cleaning up existing services..."
sudo systemctl stop kiosk.service 2>/dev/null || true
sudo systemctl disable kiosk.service 2>/dev/null || true
sudo systemctl stop kiosk-display.service 2>/dev/null || true
sudo systemctl disable kiosk-display.service 2>/dev/null || true
sudo rm -f /etc/systemd/system/kiosk.service
sudo rm -f /etc/systemd/system/kiosk-display.service

# Create app directory
echo "📁 Creating application directory..."
sudo mkdir -p /opt/$APP_NAME
sudo chown pi:pi /opt/$APP_NAME

# Clone repository and copy dist files
echo "📥 Downloading application files..."
cd /tmp
rm -rf temp-repo 2>/dev/null || true
git clone $GITHUB_REPO_URL temp-repo
sudo cp -r temp-repo/$DIST_FOLDER_PATH/* /opt/$APP_NAME/
sudo chown -R www-data:www-data /opt/$APP_NAME
rm -rf temp-repo

# Configure nginx
echo "🌐 Configuring web server..."
sudo tee /etc/nginx/sites-available/$APP_NAME > /dev/null <<EOF
server {
    listen 80 default_server;
    listen [::]:80 default_server;
    
    root /opt/$APP_NAME;
    index index.html;
    
    server_name _;
    
    location / {
        try_files \$uri \$uri/ /index.html;
    }
    
    # Cache static assets
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
}
EOF

# Remove default nginx site and enable our app
sudo rm -f /etc/nginx/sites-enabled/default
sudo ln -sf /etc/nginx/sites-available/$APP_NAME /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx

# Enable nginx to start on boot
sudo systemctl enable nginx

# Fix X11 permissions - CRITICAL for Pi Zero
echo "🔐 Configuring X11 permissions..."
echo 'allowed_users=anybody' | sudo tee /etc/X11/Xwrapper.config

# Add pi user to necessary groups
sudo usermod -a -G video,audio,input,dialout,plugdev,gpio pi

# Configure auto-login for pi user
echo "👤 Configuring auto-login..."
sudo systemctl set-default multi-user.target
sudo mkdir -p /etc/systemd/system/getty@tty1.service.d
sudo tee /etc/systemd/system/getty@tty1.service.d/override.conf > /dev/null <<EOF
[Service]
ExecStart=
ExecStart=-/sbin/agetty --autologin pi --noclear %I \$TERM
EOF

# Create the working kiosk startup script based on Pi model
echo "🖥️  Creating kiosk startup script..."

# Create the script with the appropriate browser command embedded
if [[ "$PI_MODEL" =~ ^(900092|900093|920092|920093)$ ]]; then
    # Pi Zero 1st gen - use Firefox
    cat > /home/pi/kiosk-start.sh << 'SCRIPT_END'
# Replace your kiosk-start.sh with this version that maintains status throughout

#!/bin/bash

# Status display function - writes to both console and a status file
log_status() {
    local message="$1"
    local timestamp=$(date '+%H:%M:%S')
    echo "[$timestamp] 🚀 $message" | tee -a /tmp/kiosk-status.log
    # Also display on console
    echo -e "\033[2J\033[H" # Clear screen and go to top
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo "             🚀 DASHBOARD STARTUP STATUS"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo ""
    tail -10 /tmp/kiosk-status.log 2>/dev/null || echo "Starting up..."
    echo ""
    echo "Current: $message"
    echo ""
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
}

# Initialize status log
echo "Dashboard startup initiated at $(date)" > /tmp/kiosk-status.log

log_status "Initializing kiosk mode"

# Check if we're on the main console
if [ "$(tty)" != "/dev/tty1" ]; then
    log_status "Not on main console, exiting"
    exit 0
fi

# Wait a moment for system to settle
log_status "Waiting for system to stabilize"
sleep 3

# Kill any existing processes
log_status "Cleaning up existing processes"
sudo pkill -f "X " 2>/dev/null || true
sudo pkill -f "chromium" 2>/dev/null || true
sudo pkill -f "firefox" 2>/dev/null || true
sleep 2

# Check if nginx is running and serving content
log_status "Checking web server status"
WEB_SERVER_READY=false
for i in {1..15}; do
    if curl -s http://localhost > /dev/null 2>&1; then
        log_status "✅ Web server is responding"
        WEB_SERVER_READY=true
        break
    fi
    log_status "⏳ Waiting for web server... attempt $i/15"
    sleep 2
done

if [ "$WEB_SERVER_READY" = false ]; then
    log_status "❌ Web server not responding after 30 seconds"
    log_status "🔧 Attempting to restart nginx..."
    sudo systemctl restart nginx
    sleep 3
    if curl -s http://localhost > /dev/null 2>&1; then
        log_status "✅ Web server recovered"
    else
        log_status "❌ Web server failed to start - check logs"
        echo "Debug: Run 'sudo systemctl status nginx' and 'sudo journalctl -u nginx'"
        read -p "Press Enter to continue anyway or Ctrl+C to abort..."
    fi
fi

# Set up environment
log_status "Setting up display environment"
export DISPLAY=:0
export XDG_RUNTIME_DIR=/run/user/$(id -u)
mkdir -p $XDG_RUNTIME_DIR

# Start X server with proper permissions
log_status "Starting X server (this may take 10-15 seconds)"
sudo X :0 &
X_PID=$!

# Wait for X to start with timeout
log_status "Waiting for X server to become ready"
X_READY=false
for i in {1..20}; do
    if DISPLAY=:0 xset q >/dev/null 2>&1; then
        log_status "✅ X server is ready"
        X_READY=true
        break
    fi
    log_status "⏳ X server starting... $i/20"
    sleep 1
done

if [ "$X_READY" = false ]; then
    log_status "❌ X server failed to start properly"
    log_status "🔧 Debug info: ps aux | grep X"
    ps aux | grep X | grep -v grep
    read -p "Press Enter to continue anyway or Ctrl+C to abort..."
fi

# Verify X is still running
if ! ps -p $X_PID > /dev/null 2>/dev/null; then
    log_status "❌ X server process died"
    exit 1
fi

# Configure display settings
log_status "Configuring display settings"
DISPLAY=:0 xset -dpms 2>/dev/null &
DISPLAY=:0 xset s off 2>/dev/null &
DISPLAY=:0 xset s noblank 2>/dev/null &

# Hide mouse cursor
# log_status "Hiding mouse cursor"
# DISPLAY=:0 unclutter -idle 5 -root &

# Start window manager
log_status "Starting window manager"
DISPLAY=:0 openbox &
sleep 3

# Final check - test if we can actually display something
log_status "Testing display capability"
if ! DISPLAY=:0 xwininfo -root >/dev/null 2>&1; then
    log_status "❌ Display test failed"
    exit 1
fi

log_status "✅ Display system ready"

# Start the browser
log_status "Starting browser (Firefox ESR)"
log_status "⏳ Browser may take 20-30 seconds to fully load..."

# Show a temporary "Loading" message on screen while browser starts
DISPLAY=:0 xterm -geometry 80x24+50+50 -title "Loading" -e "
echo '🚀 Dashboard Loading...'
echo ''
echo 'Browser is starting up.'
echo 'This window will close automatically.'
echo ''
echo 'Status: Launching Firefox ESR...'
sleep 5
echo 'Status: Loading dashboard content...'
sleep 10
echo 'Status: Almost ready...'
sleep 5
" &
XTERM_PID=$!

# Start Firefox ESR in kiosk mode
DISPLAY=:0 firefox-esr --kiosk --private-window http://localhost &
FIREFOX_PID=$!

# Wait a bit for Firefox to start
sleep 15

# Close the loading terminal
kill $XTERM_PID 2>/dev/null || true

# Final status
log_status "🎉 Kiosk mode started successfully!"
log_status "Firefox PID: $FIREFOX_PID"
log_status "X Server PID: $X_PID"
log_status "Dashboard should now be visible"

# Keep the script running but stop status updates
echo "Kiosk is now running. Press Ctrl+C to stop."
wait
SCRIPT_END
else
    # Other Pi models - use Chromium
    cat > /home/pi/kiosk-start.sh << 'SCRIPT_END'
#!/bin/bash

echo "Starting kiosk mode..."

# Check if we're on the main console
if [ "$(tty)" != "/dev/tty1" ]; then
    echo "Not on main console, exiting"
    exit 0
fi

# Wait a moment for system to settle
sleep 3

# Check if nginx is running and serving content
echo "Checking web server..."
for i in {1..10}; do
    if curl -s http://localhost > /dev/null; then
        echo "Web server is ready"
        break
    fi
    echo "Waiting for web server... ($i/10)"
    sleep 2
done

# Kill any existing processes
sudo pkill -f "X " 2>/dev/null || true
sudo pkill -f "chromium" 2>/dev/null || true
sudo pkill -f "firefox" 2>/dev/null || true
sleep 2

# Set up environment
export DISPLAY=:0
export XDG_RUNTIME_DIR=/run/user/$(id -u)

# Create runtime directory if it doesn't exist
mkdir -p $XDG_RUNTIME_DIR

# Start X server with proper permissions
echo "Starting X server..."
sudo X :0 &
X_PID=$!

# Wait for X to start
sleep 5

# Verify X is running
if ! ps -p $X_PID > /dev/null; then
    echo "X server failed to start"
    exit 1
fi

# Configure display settings
DISPLAY=:0 xset -dpms 2>/dev/null &
DISPLAY=:0 xset s off 2>/dev/null &
DISPLAY=:0 xset s noblank 2>/dev/null &

# Hide mouse cursor
DISPLAY=:0 unclutter -idle 5 -root &

# Start window manager
DISPLAY=:0 openbox &
sleep 3

echo "Starting Chromium..."
# Start Chromium in kiosk mode
DISPLAY=:0 chromium-browser \
    --no-sandbox \
    --disable-dev-shm-usage \
    --disable-gpu \
    --no-first-run \
    --disable-infobars \
    --disable-session-crashed-bubble \
    --disable-suggestions-ui \
    --disable-translate \
    --disable-web-security \
    --disable-features=VizDisplayCompositor \
    --disable-ipc-flooding-protection \
    --disable-background-timer-throttling \
    --disable-backgrounding-occluded-windows \
    --disable-renderer-backgrounding \
    --kiosk \
    --incognito \
    --autoplay-policy=no-user-gesture-required \
    http://localhost &

# Keep the script running
echo "Kiosk mode started successfully!"
wait
SCRIPT_END
fi

chmod +x /home/pi/kiosk-start.sh

# Configure auto-start (FIXED VERSION)
echo "⚙️  Configuring auto-start..."

# Create a timestamped backup of .bashrc
BACKUP_FILE="/home/pi/.bashrc.backup.$(date +%Y%m%d_%H%M%S)"
if [ -f /home/pi/.bashrc ]; then
    cp /home/pi/.bashrc "$BACKUP_FILE"
    echo "📋 Created backup: $BACKUP_FILE"
fi

# Always create a clean, working .bashrc
echo "🆕 Creating clean .bashrc..."
cat > /home/pi/.bashrc << 'BASHRC_EOF'
# ~/.bashrc: executed by bash(1) for non-login shells.

# If not running interactively, don't do anything
case $- in
    *i*) ;;
      *) return;;
esac

# Don't put duplicate lines or lines starting with space in the history.
HISTCONTROL=ignoreboth

# Append to the history file, don't overwrite it
shopt -s histappend

# For setting history length see HISTSIZE and HISTFILESIZE in bash(1)
HISTSIZE=1000
HISTFILESIZE=2000

# Check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize

# Make less more friendly for non-text input files, see lesspipe(1)
[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"

# Set variable identifying the chroot you work in (used in the prompt below)
if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then
    debian_chroot=$(cat /etc/debian_chroot)
fi

# Set a fancy prompt (non-color, unless we know we "want" color)
case "$TERM" in
    xterm-color|*-256color) color_prompt=yes;;
esac

if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
unset color_prompt

# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
    PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
    ;;
*)
    ;;
esac

# Enable color support of ls and also add handy aliases
if [ -x /usr/bin/dircolors ]; then
    test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)"
    alias ls='ls --color=auto'
    alias grep='grep --color=auto'
    alias fgrep='fgrep --color=auto'
    alias egrep='egrep --color=auto'
fi

# Colored GCC warnings and errors
export GCC_COLORS='error=01;31:warning=01;35:note=01;36:caret=01;32:locus=01:quote=01'

# Some more ls aliases
alias ll='ls -alF'
alias la='ls -A'
alias l='ls -CF'

# Auto-start kiosk mode on main console
if [ "$(tty)" = "/dev/tty1" ]; then
    /home/pi/kiosk-start.sh
fi
BASHRC_EOF

# Test .bashrc syntax (critical step)
echo "🧪 Testing .bashrc syntax..."
if bash -n /home/pi/.bashrc; then
    echo "✅ .bashrc syntax is valid"
else
    echo "❌ .bashrc has syntax errors - this should not happen with clean version"
    echo "⚠️  Restoring from backup if available..."
    if [ -f "$BACKUP_FILE" ]; then
        cp "$BACKUP_FILE" /home/pi/.bashrc
        echo "Restored from backup. Manual configuration may be required."
    fi
    exit 1
fi

# Create update script for easy app updates
echo "🔄 Creating update script..."
tee /home/pi/update-app.sh > /dev/null <<UPDATE_EOF
#!/bin/bash
echo "Updating $APP_NAME..."
cd /tmp
rm -rf temp-repo 2>/dev/null || true
git clone $GITHUB_REPO_URL temp-repo
sudo systemctl stop nginx
sudo cp -r temp-repo/$DIST_FOLDER_PATH/* /opt/$APP_NAME/
sudo chown -R www-data:www-data /opt/$APP_NAME
sudo systemctl start nginx
rm -rf temp-repo
echo "Update complete! App will reload automatically."
UPDATE_EOF

chmod +x /home/pi/update-app.sh

# Create troubleshooting script
echo "🔧 Creating troubleshooting script..."
tee /home/pi/kiosk-debug.sh > /dev/null <<DEBUG_EOF
#!/bin/bash
echo "=== Kiosk Debug Information ==="
echo "Date: \$(date)"
echo ""
echo "🌐 Web server status:"
curl -s http://localhost > /dev/null && echo "✅ Nginx serving content" || echo "❌ Nginx not responding"
echo ""
echo "🖥️  Display processes:"
ps aux | grep -E "(X|chromium|firefox)" | grep -v grep || echo "No display processes running"
echo ""
echo "🔍 Environment:"
echo "DISPLAY: \$DISPLAY"
echo "TTY: \$(tty)"
echo "User: \$(whoami)"
echo ""
echo "📁 File permissions:"
ls -la /home/pi/kiosk-start.sh
echo ""
echo "🧪 .bashrc syntax test:"
bash -n /home/pi/.bashrc && echo "✅ .bashrc syntax OK" || echo "❌ .bashrc has errors"
echo ""
echo "🔄 Manual kiosk start test:"
echo "Run: /home/pi/kiosk-start.sh"
DEBUG_EOF

chmod +x /home/pi/kiosk-debug.sh

# Set up GPU memory split for better graphics performance
echo "🎮 Optimizing GPU settings..."
if ! grep -q "gpu_mem" /boot/config.txt; then
    echo "gpu_mem=128" | sudo tee -a /boot/config.txt
fi

# Add HDMI force hotplug in case of display issues
if ! grep -q "hdmi_force_hotplug" /boot/config.txt; then
    echo "hdmi_force_hotplug=1" | sudo tee -a /boot/config.txt
fi

# Disable unnecessary services to free up resources
echo "⚡ Optimizing system performance..."
sudo systemctl disable bluetooth 2>/dev/null || true
sudo systemctl disable wifi-country 2>/dev/null || true
sudo systemctl disable triggerhappy 2>/dev/null || true

# Cleanup systemd
sudo systemctl daemon-reload

echo ""
echo "✅ Setup complete!"
echo ""
echo "📁 Files created:"
echo "  • /home/pi/kiosk-start.sh - Main kiosk startup script"
echo "  • /home/pi/update-app.sh - Update app from GitHub"
echo "  • /home/pi/kiosk-debug.sh - Debug and troubleshoot issues"
echo "  • $BACKUP_FILE - Backup of original .bashrc"
echo ""
echo "🔄 Next steps:"
echo "1. Reboot now: sudo reboot"
echo "2. Pi will auto-login and start kiosk mode"
echo "3. Your dashboard will display full-screen"
echo ""
echo "🐛 If you have issues after reboot:"
echo "1. SSH in: ssh pi@your-pi-ip"
echo "2. Run debug: ./kiosk-debug.sh"
echo "3. Manual start: ./kiosk-start.sh"
echo "4. Check web server: curl http://localhost"
echo ""
echo "🔄 Future updates:"
echo "Run: ./update-app.sh"
echo ""
echo "Ready to reboot!"