#!/usr/bin/env bash
# Pi 3B+ wall panel: turns Raspberry Pi OS Lite into a full-screen Home Assistant kiosk.
# Run ON THE PI as your normal user (not root):
#   bash kiosk-setup.sh "http://homeassistant.local:8123/wall-panel/home"
# Re-run any time with a new URL to change the page.
set -euo pipefail

URL="${1:-http://homeassistant.local:8123/wall-panel/home}"
if [[ $EUID -eq 0 ]]; then echo "Run as your normal user, not with sudo."; exit 1; fi

echo "==> Installing a minimal X server, Openbox and Chromium (no desktop)"
sudo apt-get update
sudo apt-get install -y --no-install-recommends \
  xserver-xorg xserver-xorg-input-libinput x11-xserver-utils xinit openbox
sudo apt-get install -y --no-install-recommends chromium \
  || sudo apt-get install -y --no-install-recommends chromium-browser
BROWSER="$(command -v chromium || command -v chromium-browser)"

echo "==> Auto-login to the console on boot"
sudo raspi-config nonint do_boot_behaviour B2

echo "==> Saving kiosk URL to ~/kiosk.conf"
echo "KIOSK_URL=\"$URL\"" > ~/kiosk.conf

echo "==> Start X automatically on the first console (no mouse cursor)"
touch ~/.bash_profile
if ! grep -q "startx" ~/.bash_profile; then
  cat >> ~/.bash_profile <<'EOP'

# Wall panel: start the kiosk on the physical screen only (not over SSH)
if [[ -z "${DISPLAY:-}" && "$(tty)" == "/dev/tty1" ]]; then
  exec startx -- -nocursor
fi
EOP
fi

echo "==> Openbox autostart: screen always on, then Chromium in kiosk mode"
mkdir -p ~/.config/openbox
cat > ~/.config/openbox/autostart <<EOA
# Keep the screen on (see the guide for a 'sleep after 5 min' option)
xset s off
xset s noblank
xset -dpms

# Stop Chromium showing "restore pages?" after a power cut
PREFS=~/.config/chromium/Default/Preferences
if [ -f "\$PREFS" ]; then
  sed -i 's/"exited_cleanly":false/"exited_cleanly":true/; s/"exit_type":"[^"]*"/"exit_type":"Normal"/' "\$PREFS"
fi

. ~/kiosk.conf
# Relaunch Chromium if it ever crashes
while true; do
  $BROWSER \\
    --kiosk --noerrdialogs --disable-infobars --no-first-run \\
    --password-store=basic \\
    --disable-features=Translate,TranslateUI \\
    --overscroll-history-navigation=0 --disable-pinch \\
    --check-for-update-interval=31536000 \\
    --enable-low-end-device-mode \\
    --touch-events=enabled --force-dark-mode \\
    "\$KIOSK_URL"
  sleep 3
done &
EOA

echo
echo "Done. Reboot with: sudo reboot"
echo "First boot: plug in a USB keyboard once to log in to Home Assistant as your wall-panel user."
