#!/usr/bin/env bash
# Aurora Deck — Display Configuration Script
#
# Configures the labwc Wayland compositor, maliit on-screen keyboard, and
# Chromium app mode for a Raspberry Pi + 7" DSI touchscreen display.
#
# Run this on your Raspberry Pi after the initial OS setup:
#   bash configure-aurora-deck-display.sh
#
# You can pass your Aurora Deck URL as an argument to skip the prompt:
#   bash configure-aurora-deck-display.sh https://your-aurora-deck-url

set -euo pipefail

# ── Helper ────────────────────────────────────────────────────────────────────
info()  { echo "[aurora] $*"; }
warn()  { echo "[aurora] WARNING: $*" >&2; }
abort() { echo "[aurora] ERROR: $*" >&2; exit 1; }

# ── Aurora Deck URL ───────────────────────────────────────────────────────────
if [ -n "${1:-}" ]; then
  AURORA_URL="$1"
else
  echo ""
  read -rp "  Enter your Aurora Deck URL (e.g. https://auroradeck.com): " AURORA_URL
fi

[[ "$AURORA_URL" =~ ^https?:// ]] || abort "URL must start with http:// or https://"

# ── Install dependencies ──────────────────────────────────────────────────────
info "Checking dependencies..."

MISSING_PKGS=()
command -v maliit-server &>/dev/null || MISSING_PKGS+=(maliit-keyboard)

if [ ${#MISSING_PKGS[@]} -gt 0 ]; then
  info "Installing: ${MISSING_PKGS[*]}"
  sudo apt-get update -qq
  sudo apt-get install -y "${MISSING_PKGS[@]}"
else
  info "All dependencies already installed."
fi

# ── Backup helper ─────────────────────────────────────────────────────────────
backup_if_exists() {
  local file="$1"
  if [ -f "$file" ]; then
    local backup="${file}.bak.$(date +%Y%m%d%H%M%S)"
    warn "$(basename "$file") already exists — backing up to $(basename "$backup")"
    cp "$file" "$backup"
  fi
}

# ── 1. Disable autotouch ──────────────────────────────────────────────────────
# Raspberry Pi OS ships /usr/bin/autotouch which runs at login and overwrites
# rc.xml with mouseEmulation="yes", breaking native touch scrolling. Hide it
# with a user-level XDG autostart override.
info "Disabling autotouch..."
mkdir -p "$HOME/.config/autostart"
cat > "$HOME/.config/autostart/autotouch.desktop" << 'EOF'
[Desktop Entry]
Hidden=true
EOF

# ── 2. labwc autostart ────────────────────────────────────────────────────────
# The autostart detects the touch device via libinput on every boot and writes
# rc.xml fresh, so the correct device name and display output are always used.
info "Writing ~/.config/labwc/autostart..."
mkdir -p "$HOME/.config/labwc"
backup_if_exists "$HOME/.config/labwc/autostart"

cat > "$HOME/.config/labwc/autostart" << EOF
TOUCH=\$(libinput list-devices | tr '\n' @ | sed 's/@@/\n/g' | grep "Capabilities:.*touch" | sed 's/Device:[ \t]*//' | cut -d @ -f 1)
DISPLAY_OUT=\$(wlr-randr | grep '^\S' | cut -d ' ' -f 1)

if [ -n "\$TOUCH" ] && [ -n "\$DISPLAY_OUT" ]; then
  mkdir -p ~/.config/labwc
  cat > ~/.config/labwc/rc.xml << RCEOF
<?xml version="1.0"?>
<openbox_config xmlns="http://openbox.org/3.4/rc">
  <theme>
    <maximizedDecoration>none</maximizedDecoration>
    <keepBorder>no</keepBorder>
  </theme>
  <touch deviceName="\$TOUCH"
         mapToOutput="\$DISPLAY_OUT"
         mouseEmulation="no"/>
  <windowRules>
    <windowRule identifier="chromium"
                matchType="identifier"
                serverDecoration="yes">
      <action name="Maximize"/>
    </windowRule>
  </windowRules>
</openbox_config>
RCEOF
  labwc --reconfigure
fi

maliit-server &
chromium --app=${AURORA_URL} \\
  --start-maximized \\
  --noerrdialogs --disable-infobars \\
  --disable-session-crashed-bubble --no-first-run \\
  --hide-scrollbars --touch-events=enabled \\
  --ozone-platform=wayland --password-store=basic \\
  --enable-wayland-ime &
EOF

# ── Done ──────────────────────────────────────────────────────────────────────
echo ""
echo "  Display configuration complete. Files written:"
echo "    ~/.config/autostart/autotouch.desktop"
echo "    ~/.config/labwc/autostart"
echo ""
echo "  Aurora Deck URL set to: ${AURORA_URL}"
echo ""
echo "  Reboot to apply all changes:"
echo "    sudo reboot"
echo ""
