#!/bin/bash
# Turn a fresh Debian trixie + LXDE installation into a PDF slideshow kiosk.
# Usage (as root): ./kiosk-setup.sh /path/to/slides.pdf [seconds_per_slide] [user]
# Update slides later: copy new file to /srv/kiosk/slides.pdf and press "q".

set -euo pipefail

PDF_SRC="${1:-}"
DELAY="${2:-10}"
KIOSK_USER="${3:-kiosk}"
KIOSK_DIR="/srv/kiosk"

[[ $EUID -eq 0 ]] || { echo "Please run as root." >&2; exit 1; }
[[ -n "$PDF_SRC" && -f "$PDF_SRC" ]] || { echo "Usage: $0 slides.pdf [seconds] [user]" >&2; exit 1; }
[[ "$DELAY" =~ ^[0-9]+$ ]] || { echo "seconds must be an integer." >&2; exit 1; }

export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get install -y --no-install-recommends impressive lightdm unclutter-xfixes x11-xserver-utils
apt-get purge -y xscreensaver light-locker 2>/dev/null || true

if ! id "$KIOSK_USER" >/dev/null 2>&1; then
    useradd --create-home --shell /bin/bash --comment "Kiosk" "$KIOSK_USER"
    passwd --delete "$KIOSK_USER" >/dev/null
fi
KIOSK_HOME="$(getent passwd "$KIOSK_USER" | cut -d: -f6)"

install -d -m 0755 "$KIOSK_DIR"
install -m 0644 "$PDF_SRC" "$KIOSK_DIR/slides.pdf"

cat > /usr/local/bin/kiosk-slideshow <<EOF
#!/bin/bash
# Restart impressive whenever it exits (crash, "q" pressed, file replaced).
while true; do
    [[ -f "$KIOSK_DIR/slides.pdf" ]] && impressive -a "$DELAY" -w "$KIOSK_DIR/slides.pdf"
    sleep 2
done
EOF
chmod 0755 /usr/local/bin/kiosk-slideshow

# Per-user autostart replaces the system-wide one: no panel, desktop, screensaver.
install -d -o "$KIOSK_USER" -g "$KIOSK_USER" "$KIOSK_HOME/.config" \
    "$KIOSK_HOME/.config/lxsession" "$KIOSK_HOME/.config/lxsession/LXDE"
cat > "$KIOSK_HOME/.config/lxsession/LXDE/autostart" <<'EOF'
@xset s off
@xset s noblank
@xset -dpms
@unclutter --timeout 1
@/usr/local/bin/kiosk-slideshow
EOF
chown "$KIOSK_USER:$KIOSK_USER" "$KIOSK_HOME/.config/lxsession/LXDE/autostart"

install -d /etc/lightdm/lightdm.conf.d
cat > /etc/lightdm/lightdm.conf.d/50-kiosk.conf <<EOF
[Seat:*]
autologin-user=$KIOSK_USER
autologin-user-timeout=0
autologin-session=LXDE
user-session=LXDE
xserver-command=X -s 0 -dpms
EOF
systemctl set-default graphical.target
systemctl enable lightdm.service

systemctl mask sleep.target suspend.target hibernate.target hybrid-sleep.target
install -d /etc/systemd/logind.conf.d
cat > /etc/systemd/logind.conf.d/50-kiosk.conf <<'EOF'
[Login]
HandleLidSwitch=ignore
HandleLidSwitchExternalPower=ignore
IdleAction=ignore
EOF

echo "Done. Reboot to start: systemctl reboot"
