#!/bin/bash

# Fix .bashrc corruption and setup kiosk properly

echo "🔧 Fixing .bashrc corruption..."

# Backup current .bashrc
cp /home/pi/.bashrc /home/pi/.bashrc.backup.$(date +%Y%m%d_%H%M%S)

# Clean up .bashrc - remove any malformed kiosk entries
sed -i '/# Auto-start kiosk/,/^fi$/d' /home/pi/.bashrc 2>/dev/null || true
sed -i '/tty1/d' /home/pi/.bashrc 2>/dev/null || true
sed -i '/kiosk/d' /home/pi/.bashrc 2>/dev/null || true
sed -i '/systemctl start/d' /home/pi/.bashrc 2>/dev/null || true

# Remove any orphaned fi statements
sed -i '/^fi$/d' /home/pi/.bashrc 2>/dev/null || true

# Remove empty lines at the end
sed -i -e :a -e '/^\s*$/N;ba' -e 's/\n\s*$//' /home/pi/.bashrc

echo "✅ .bashrc cleaned up"

# Now add the correct auto-start logic
echo "⚙️ Adding proper auto-start to .bashrc..."

cat >> /home/pi/.bashrc << 'BASHRC_END'

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

echo "✅ .bashrc fixed"

# Test .bashrc syntax
echo "🧪 Testing .bashrc syntax..."
if bash -n /home/pi/.bashrc; then
    echo "✅ .bashrc syntax is valid"
else
    echo "❌ .bashrc still has syntax errors. Restoring from backup..."
    cp /home/pi/.bashrc.backup.* /home/pi/.bashrc 2>/dev/null || true
    echo "Please check your .bashrc manually"
    exit 1
fi

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

echo "🖥️ Creating kiosk startup script..."

if [[ "$PI_MODEL" =~ ^(900092|900093|920092|920093)$ ]]; then
    echo "⚠️ Pi Zero 1st gen detected - using Firefox ESR"
    # Create Firefox version
    cat > /home/pi/kiosk-start.sh << 'KIOSK_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 "firefox" 2>/dev/null || true
sudo pkill -f "chromium" 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 -nocursor &
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 0.1 -root &

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

echo "Starting Firefox ESR..."
# Start Firefox ESR in kiosk mode (Pi Zero 1st gen)
DISPLAY=:0 firefox-esr --kiosk --private-window http://localhost &

# Keep the script running
echo "Kiosk mode started successfully!"
wait
KIOSK_SCRIPT_END
else
    echo "✅ Pi supports Chromium"
    # Create Chromium version
    cat > /home/pi/kiosk-start.sh << 'KIOSK_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 -nocursor &
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 0.1 -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
KIOSK_SCRIPT_END
fi

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

echo ""
echo "✅ Fix complete! Your .bashrc and kiosk script have been corrected."
echo ""
echo "📋 Next steps:"
echo "1. Test the fix: source /home/pi/.bashrc"
echo "2. If no errors, reboot: sudo reboot"
echo ""
echo "🐛 If you still have issues:"
echo "- Check .bashrc: nano /home/pi/.bashrc"
echo "- Manual test: /home/pi/kiosk-start.sh"
echo "- View backups: ls -la /home/pi/.bashrc.backup.*"