#!/bin/bash
# promptphotobooth-sysprep — prepare this Pi for imaging.
#
# Wipes every piece of user- and instance-specific state so the captured
# image boots cleanly on any customer's hardware with no traces of the
# prep machine. Idempotent; safe to re-run.
#
# Run this as root, then power off cleanly, then image the SD card.
# After running, SSH access to THIS Pi remains possible until reboot
# (existing session persists), but new connections after reboot require
# the ssh.service ExecStartPre drop-in (shipped by this package) to
# regenerate host keys.
#
# Exit codes: 0 on success, non-zero if not run as root.

set +e

if [ "$(id -u)" -ne 0 ]; then
    echo "promptphotobooth-sysprep: must run as root." >&2
    exit 1
fi

echo "=== PromptPhotoBooth sysprep — wiping instance state ==="

# -----------------------------------------------------------------------
# 1. Stop the backend + kiosk so we can wipe their state files safely.
# -----------------------------------------------------------------------
echo "[1/9] Stopping services + kiosk..."
systemctl stop promptphotobooth.service 2>/dev/null
pkill -f chromium 2>/dev/null
# rsyslog stop: prevents new /var/log writes for the remainder of this boot
systemctl stop rsyslog.service 2>/dev/null
sleep 2

# -----------------------------------------------------------------------
# 2. Delete the PromptPhotoBooth auth token files (backend JWT on disk).
#    Written by src/api/routes/auth.py:login() to ~/.promptphotobooth_token.
#    Read by AI nodes (PlotterAI, Flux, Relight, etc.) for PPB API calls.
#    Must be cleaned before imaging or the customer inherits the operator's
#    login and PPB account.
# -----------------------------------------------------------------------
echo "[2/9] Deleting auth tokens..."
rm -f /home/*/.promptphotobooth_token /root/.promptphotobooth_token
# Legacy name from earlier versions
rm -f /home/*/.plotterpix_token /root/.plotterpix_token

# -----------------------------------------------------------------------
# 3. Wipe Chromium kiosk profile (localStorage contains auth_token,
#    auth_email, chat-storage / hasCompletedOnboarding, etc.).
# -----------------------------------------------------------------------
echo "[3/9] Wiping Chromium kiosk profile + user caches..."
rm -rf /home/*/.cache/promptphotobooth-kiosk
rm -rf /home/*/.config/chromium /home/*/.cache/chromium
rm -rf /root/.cache/promptphotobooth-kiosk /root/.config/chromium /root/.cache/chromium
rm -rf /home/*/.cache/* /root/.cache/* 2>/dev/null
rm -rf /home/*/.pki /home/*/.thumbnails /home/*/.local/share/Trash 2>/dev/null

# -----------------------------------------------------------------------
# 4. Wipe runtime data under /usr/share/promptphotobooth. Projects are
#    auto-recreated on first boot; logs are written fresh.
#    NOTE: `config/` contains package-shipped templates (dnsmasq.conf,
#    hostapd.conf, boot_greetings.txt, config.json) — do NOT rm -rf
#    the whole directory, only the runtime state file (last_project.txt)
#    which otherwise makes old project names resurface via
#    ProjectService.initialize_default_project.
# -----------------------------------------------------------------------
echo "[4/9] Wiping projects + logs + runtime project-state..."
rm -rf /usr/share/promptphotobooth/projects/* 2>/dev/null
rm -rf /usr/share/promptphotobooth/logs/* 2>/dev/null
rm -rf /usr/share/promptphotobooth/conversations/* 2>/dev/null
rm -f /usr/share/promptphotobooth/config/last_project.txt 2>/dev/null

# -----------------------------------------------------------------------
# 5. NetworkManager WiFi credentials. eth0-booth is product ethernet
#    config (NOT personal), kept. Personal WiFi profiles dropped.
#    Customer adds their WiFi on first boot.
# -----------------------------------------------------------------------
echo "[5/9] Wiping personal WiFi connections + NM runtime state..."
find /etc/NetworkManager/system-connections -maxdepth 1 -type f \
    ! -name 'eth0-booth.nmconnection' -delete 2>/dev/null
rm -rf /var/lib/NetworkManager/* 2>/dev/null

# -----------------------------------------------------------------------
# 6. Host/machine identity. systemd/dbus regenerate /etc/machine-id on
#    first boot when it's zero bytes. SSH host keys are regenerated by
#    the ssh.service drop-in (ExecStartPre=ssh-keygen -A) shipped by
#    this package, so sshd can't be left unreachable.
# -----------------------------------------------------------------------
echo "[6/9] Resetting hostname + machine-id + SSH host keys..."
# Reset hostname to a generic default. Customers can rename via raspi-
# config or their own setup flow.
hostnamectl set-hostname promptphotobooth 2>/dev/null
echo promptphotobooth > /etc/hostname
# Replace any customized hostname in /etc/hosts with the generic one.
# We do this blindly by looking for 127.0.1.1 lines.
sed -i 's|^127\.0\.1\.1.*|127.0.1.1 promptphotobooth|' /etc/hosts
truncate -s 0 /etc/machine-id
rm -f /var/lib/dbus/machine-id
rm -f /var/lib/systemd/random-seed

# SSH host keys: delete the current ones and regenerate fresh ones in
# place so the shipped image boots with a working sshd immediately
# (customer can SSH in as soon as the Pi joins their network). Every
# image captured from this Pi will share these fresh host keys — that's
# the appliance trade-off, same as any other vendor-imaged Pi. If you
# want per-customer unique host keys, add a first-boot regen systemd
# oneshot that only runs when /etc/ssh/ssh_host_rsa_key is missing.
rm -f /etc/ssh/ssh_host_*
ssh-keygen -A
# Make sure ssh.service is enabled so it starts at boot. (ssh-keygen -A
# above created the keys; without explicit enable, an image from a Pi
# where ssh was manually masked/disabled would ship with ssh off.)
systemctl enable ssh 2>/dev/null

# -----------------------------------------------------------------------
# 7. Shell history + user-state breadcrumbs.
# -----------------------------------------------------------------------
echo "[7/9] Clearing shell history + user breadcrumbs..."
for home in /home/* /root; do
    [ -d "$home" ] || continue
    : > "$home/.bash_history" 2>/dev/null
    rm -f "$home/.python_history" "$home/.viminfo" "$home/.lesshst" \
          "$home/.wget-hsts" "$home/.sqlite_history" \
          "$home/.local/share/recently-used.xbel" 2>/dev/null
done

# -----------------------------------------------------------------------
# 8. System logs. Persistent + volatile.
# -----------------------------------------------------------------------
echo "[8/9] Wiping /var/log + apt lists + /tmp..."
find /var/log -type f \( -name '*.gz' -o -name '*.log.[0-9]*' -o -name '*.[0-9]' \) -delete 2>/dev/null
find /var/log -type f -exec truncate -s 0 {} \; 2>/dev/null
rm -rf /var/lib/apt/lists/* 2>/dev/null
rm -rf /tmp/* /tmp/.[!.]* 2>/dev/null

# -----------------------------------------------------------------------
# 9. Rotate + vacuum the journal (volatile storage — vanishes on reboot
#    anyway, but this drops the current-boot traces right now). Final
#    sync to flush all pending writes.
# -----------------------------------------------------------------------
echo "[9/9] Rotating journal + syncing..."
journalctl --rotate >/dev/null 2>&1
journalctl --vacuum-time=1s >/dev/null 2>&1
sync

echo ""
echo "=== sysprep complete ==="
echo ""
echo "Next steps:"
echo "  1. Verify state: 'systemctl is-active promptphotobooth.service' → inactive"
echo "  2. Power off cleanly: 'sudo poweroff'"
echo "  3. Pull the SD card and image it."
echo ""
echo "On first boot of the imaged Pi:"
echo "  - /etc/machine-id is regenerated by systemd"
echo "  - SSH host keys are regenerated by ssh.service's ExecStartPre drop-in"
echo "  - promptphotobooth.service auto-starts and creates a fresh empty project"
echo "  - Customer sees login + onboarding (no stale session)"
echo ""
