#!/bin/bash

echo "🍓 Adhaan Raspberry Pi Kiosk Setup"
echo "=================================="

# Update systeem
echo "📦 Systeem bijwerken..."
sudo apt update -y
sudo apt upgrade -y

# Installeer Docker
echo "🐳 Docker installeren..."
curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh
sudo usermod -aG docker $USER
rm get-docker.sh

# Installeer Docker Compose
echo "🔧 Docker Compose installeren..."
sudo apt install -y docker-compose

# Installeer GUI componenten voor kiosk mode
echo "🖥️  GUI componenten installeren..."
sudo apt install -y --no-install-recommends \
    xserver-xorg \
    x11-xserver-utils \
    xinit \
    openbox \
    chromium-browser \
    unclutter

# Configureer HDMI audio automatisch
echo "🔊 HDMI audio automatisch configureren..."
sudo raspi-config nonint do_audio 2  # Force HDMI audio

# Maak kiosk script
echo "📝 Kiosk script aanmaken..."
cat > /home/$USER/kiosk.sh << 'EOF'
#!/bin/bash
sleep 2

echo "Starting Adhaan Kiosk..."

# Forceer HDMI audio output
echo "🔊 HDMI audio configureren..."
amixer cset numid=3 2  # 0=auto, 1=headphones, 2=hdmi
sudo raspi-config nonint do_audio 2  # Force HDMI audio

# Zet volume op redelijk niveau (70%)
amixer set PCM 70%

# Start Docker containers
cd /home/pi/adhan
echo "Starting Docker containers..."
docker-compose -f docker-compose-pi.yml up -d

# Wacht tot containers draaien
sleep 5

# Sluit eventuele andere browsers
pkill -f chromium-browser 2>/dev/null || true

# Start browser in kiosk mode met audio optimalisaties
echo "Starting browser..."
/usr/bin/chromium-browser \
    --kiosk \
    --start-maximized \
    --noerrdialogs \
    --disable-infobars \
    --disable-session-crashed-bubble \
    --disable-restore-session-state \
    --disable-background-timer-throttling \
    --disable-backgrounding-occluded-windows \
    --disable-renderer-backgrounding \
    --disable-features=TranslateUI \
    --disable-ipc-flooding-protection \
    --enable-features=OverlayScrollbar \
    --no-first-run \
    --fast \
    --fast-start \
    --disable-default-apps \
    --disable-popup-blocking \
    --disable-prompt-on-repost \
    --disable-hang-monitor \
    --disable-background-networking \
    --aggressive-cache-discard \
    --memory-pressure-off \
    --max_old_space_size=100 \
    --force-device-scale-factor=1 \
    --autoplay-policy=no-user-gesture-required \
    --allow-running-insecure-content \
    --disable-web-security \
    --disable-features=VizDisplayCompositor \
    --disable-translate \
    --disable-features=Translate \
    --disable-component-extensions-with-background-pages \
    --lang=nl \
    http://localhost:5090 &

echo "Kiosk started!"
EOF

chmod +x /home/$USER/kiosk.sh

# Configureer autostart
echo "⚙️  Autostart configureren..."
sudo mkdir -p /etc/xdg/openbox
cat > /tmp/autostart << 'EOF'
# Schakel power management uit
xset -dpms
xset s noblank
xset s off

# Verberg cursor na 3 seconden
unclutter -idle 3 -root &

# Verwijder crash berichten
sed -i 's/"exited_cleanly":false/"exited_cleanly":true/' ~/.config/chromium/'Local State' 2>/dev/null || true
sed -i 's/"exited_cleanly":false/"exited_cleanly":true/; s/"exit_type":"[^"]\+"/"exit_type":"Normal"/' ~/.config/chromium/Default/Preferences 2>/dev/null || true

# Start kiosk
/home/USER_PLACEHOLDER/kiosk.sh
EOF

sed "s/USER_PLACEHOLDER/$USER/g" /tmp/autostart | sudo tee /etc/xdg/openbox/autostart > /dev/null

# Configureer automatische X start
echo "🚀 Automatische X start configureren..."
if ! grep -q "startx" ~/.bash_profile 2>/dev/null; then
    echo '[[ -z $DISPLAY && $XDG_VTNR -eq 1 ]] && startx -- -nocursor' >> ~/.bash_profile
fi

# Configureer automatische login (VERBETERD)
echo "👤 Automatische login configureren..."
sudo raspi-config nonint do_boot_behaviour B4

# Extra: Schakel splash screen uit voor snellere boot
echo "🚀 Boot optimalisaties..."
sudo raspi-config nonint do_boot_splash 1

# ⚡ NIEUWE SNELHEIDSOPTIMALISATIES
echo "⚡ Extra boot optimalisaties..."

# Disable onnodig services
sudo systemctl disable bluetooth.service 2>/dev/null || true
sudo systemctl disable hciuart.service 2>/dev/null || true
sudo systemctl disable triggerhappy.service 2>/dev/null || true
sudo systemctl disable avahi-daemon.service 2>/dev/null || true
sudo systemctl disable ModemManager.service 2>/dev/null || true

# Boot parameters optimaliseren
echo "# Snellere boot optimalisaties" | sudo tee -a /boot/config.txt
echo "boot_delay=0" | sudo tee -a /boot/config.txt
echo "disable_splash=1" | sudo tee -a /boot/config.txt

# Kernel boot optimalisaties
if ! grep -q "quiet" /boot/cmdline.txt; then
    sudo sed -i 's/$/ quiet/' /boot/cmdline.txt
fi

# 💀 HARDCORE OPTIMALISATIES
echo "💀 Hardcore snelheidsoptimalisaties..."

# Disable meer services
sudo systemctl disable systemd-timesyncd.service 2>/dev/null || true
sudo systemctl disable rsyslog.service 2>/dev/null || true
sudo systemctl disable systemd-journal-flush.service 2>/dev/null || true
sudo systemctl disable NetworkManager-wait-online.service 2>/dev/null || true

# RAM optimalisaties
echo "# RAM optimalisaties" | sudo tee -a /boot/config.txt
echo "gpu_mem=64" | sudo tee -a /boot/config.txt
echo "arm_freq=1200" | sudo tee -a /boot/config.txt

# SD kaart optimalisaties  
echo "# SD kaart optimalisaties" | sudo tee -a /boot/config.txt
echo "dtparam=sd_overclock=100" | sudo tee -a /boot/config.txt

# Kernel parameters voor snelheid
if ! grep -q "fastboot" /boot/cmdline.txt; then
    sudo sed -i 's/$/ fastboot/' /boot/cmdline.txt
fi

# Preload Docker images
echo "🐳 Docker images voorladen..."
cd /home/$USER/adhan
docker-compose -f docker-compose-pi.yml pull 2>/dev/null || true

# Extra: Schakel wachtwoord login uit voor console (optioneel)
echo "🔒 Console login optimaliseren..."
sudo raspi-config nonint do_boot_behaviour B2

# Schakel lightdm greeter uit (geen login scherm)
echo "🖥️  Login scherm uitschakelen..."
sudo systemctl set-default multi-user.target
sudo systemctl disable lightdm 2>/dev/null || true

# Configureer automatische startx zonder login manager
cat > /tmp/getty-override.conf << 'EOF'
[Service]
ExecStart=
ExecStart=-/sbin/agetty --autologin USER_PLACEHOLDER --noclear %I $TERM
EOF

sed "s/USER_PLACEHOLDER/$USER/g" /tmp/getty-override.conf | sudo tee /etc/systemd/system/getty@tty1.service.d/override.conf > /dev/null
sudo mkdir -p /etc/systemd/system/getty@tty1.service.d/

# Maak systemd service voor Docker (GEOPTIMALISEERD)
echo "🔄 Docker service configureren..."
cat > /tmp/adhan-docker.service << 'EOF'
[Unit]
Description=Adhaan Docker Services
Requires=docker.service
After=docker.service

[Service]
Type=forking
RemainAfterExit=yes
WorkingDirectory=/home/USER_PLACEHOLDER/adhan
ExecStart=/usr/bin/docker-compose -f docker-compose-pi.yml up -d
ExecStop=/usr/bin/docker-compose -f docker-compose-pi.yml down
TimeoutStartSec=0

[Install]
WantedBy=multi-user.target
EOF

sed "s/USER_PLACEHOLDER/$USER/g" /tmp/adhan-docker.service | sudo tee /etc/systemd/system/adhan-docker.service > /dev/null
sudo systemctl enable adhan-docker.service

# Test Docker setup
echo "🧪 Docker setup testen..."
cd /home/$USER/adhan
if docker-compose -f docker-compose-pi.yml config > /dev/null 2>&1; then
    echo "✅ Docker configuratie OK"
else
    echo "❌ Docker configuratie probleem"
fi

echo ""
echo "✅ Setup voltooid!"
echo ""
echo "📋 Volgende stappen:"
echo "1. Herstart de Pi: sudo reboot"
echo "2. De Pi start automatisch ZONDER login scherm"
echo "3. Docker containers starten automatisch"
echo "4. Webpagina opent automatisch fullscreen"
echo ""
echo "🔧 Handmatige bediening:"
echo "- Alt+F4: Sluit browser"
echo "- Ctrl+Alt+T: Open terminal"
echo "- sudo systemctl status adhan-docker: Check Docker status"
echo ""
echo "⚠️  BELANGRIJK:"
echo "- Geen login scherm meer na herstart"
echo "- SSH blijft beschikbaar voor remote toegang"
echo "- Voor lokale terminal: Ctrl+Alt+F2"
echo "- HDMI audio automatisch geconfigureerd"
echo "- Boot tijd geoptimaliseerd: ~30-45 seconden" 