#!/bin/bash
# One-time fix for reTerminal DM after first-boot: splash, Plymouth theme, rotation, wallpaper.
# Run on the device as root (e.g. sudo bash fix-reterminal-display.sh).
# Or run over SSH: ssh pi@DEVICE_IP 'sudo bash -s' < fix-reterminal-display.sh

set -e
PI_USER="${PI_USER:-pi}"
PI_HOME="/home/$PI_USER"
CFG_PATH="/boot/firmware/config.txt"
[[ -f "$CFG_PATH" ]] || CFG_PATH="/boot/config.txt"

echo "=== Fixing boot splash (disable_splash=0) ==="
if [[ -f "$CFG_PATH" ]]; then
  sed -i 's/^disable_splash=1$/disable_splash=0/' "$CFG_PATH" || true
  grep -q '^disable_splash=' "$CFG_PATH" || echo 'disable_splash=0' >> "$CFG_PATH"
  echo "Done. config: $(grep disable_splash "$CFG_PATH")"
fi

echo "=== Fixing Plymouth theme (custom only, no duplicate [Daemon]) ==="
if [[ -f /etc/plymouth/plymouthd.conf ]]; then
  sed -i '/^Theme=/d' /etc/plymouth/plymouthd.conf
  sed -i '/^\[Daemon\]$/d' /etc/plymouth/plymouthd.conf
  grep -q '^\[Daemon\]' /etc/plymouth/plymouthd.conf || echo '[Daemon]' >> /etc/plymouth/plymouthd.conf
  echo 'Theme=custom' >> /etc/plymouth/plymouthd.conf
  echo "Done. plymouthd.conf Theme: $(grep Theme= /etc/plymouth/plymouthd.conf)"
fi
update-initramfs -u -k all 2>/dev/null || true

echo "=== Rotation (persistent via kernel cmdline) ==="
CMDLINE_PATH="/boot/firmware/cmdline.txt"
[[ -f "$CMDLINE_PATH" ]] || CMDLINE_PATH="/boot/cmdline.txt"
if [[ -f "$CMDLINE_PATH" ]] && ! grep -q 'video=DSI-1:rotate=' "$CMDLINE_PATH"; then
  sed -i 's/$/ video=DSI-1:rotate=90/' "$CMDLINE_PATH"
  echo "Added video=DSI-1:rotate=90 to $CMDLINE_PATH (90° clockwise). Reboot to apply."
else
  echo "Rotation already set in cmdline or file missing. Current: $(grep -o 'video=DSI-1:rotate=[^ ]*' "$CMDLINE_PATH" 2>/dev/null || true)"
fi
echo ""
echo "=== Wallpaper (in labwc session, as $PI_USER) ==="
echo "  pcmanfm --set-wallpaper /usr/share/rpd-wallpaper/splash.png --wallpaper-mode=crop"
echo ""
echo "=== Reboot to apply splash, initramfs and rotation ==="
echo "  sudo reboot"
