#!/usr/bin/env bash
# wsl-setup.sh — provision SPLICE inside a WSL distribution.
#
# Run as root by SPLICE-Setup.exe:
#   wsl.exe -d <distro> -u root --cd <installer dir> -- bash ./wsl-setup.sh
#
# Adds the signed hankelsner APT repo and installs splice-terminal from it, so
# the Windows install tracks the same release stream as every Linux box and
# picks up new versions with a plain `apt upgrade`. Idempotent: safe to re-run.
#
# MUST stay LF-only — it is executed straight off a Windows filesystem and CRLF
# would make bash choke on the shebang. build.sh enforces this.

set -uo pipefail

REPO_URL="https://git.hankelsner.tech/apt"
KEYRING="/usr/share/keyrings/hankelsner.gpg"
SOURCES="/etc/apt/sources.list.d/hankelsner.list"
PKG="splice-terminal"
LOG="/var/log/splice-setup.log"

exec > >(tee -a "$LOG") 2>&1
echo "=============================================================="
echo "SPLICE setup — $(date -u '+%Y-%m-%d %H:%M:%SZ') — distro ${WSL_DISTRO_NAME:-unknown}"
echo "=============================================================="

fail() { echo; echo "SETUP FAILED: $*"; exit 1; }

[ "$(id -u)" -eq 0 ] || fail "must run as root inside WSL"

export DEBIAN_FRONTEND=noninteractive

# --- 1. WSLg check ----------------------------------------------------------
# SPLICE is a GTK window. Without WSLg there is no display for it to open on.
if [ -d /mnt/wslg ] || [ -n "${WAYLAND_DISPLAY:-}" ] || [ -n "${DISPLAY:-}" ]; then
    echo "[1/6] WSLg display support: present"
else
    echo "[1/6] WARNING: no WSLg display detected."
    echo "      SPLICE will install, but the window cannot open until WSLg is"
    echo "      available. From Windows, run:  wsl --update   then reboot."
fi

# --- 2. prerequisites -------------------------------------------------------
echo "[2/6] Installing prerequisites (curl, gnupg, ca-certificates)..."
apt-get update -qq || echo "      (apt update reported errors; continuing)"
apt-get install -y -qq ca-certificates curl gnupg \
    || fail "could not install curl/gnupg — check the distro's network access"

# --- 3. repo key ------------------------------------------------------------
echo "[3/6] Installing the hankelsner signing key..."
tmpkey="$(mktemp)"
curl -fsSL "$REPO_URL/key.gpg" -o "$tmpkey" \
    || fail "could not download $REPO_URL/key.gpg"
# The published key is ASCII-armored; dearmor it so apt accepts the keyring.
if grep -q "BEGIN PGP PUBLIC KEY" "$tmpkey"; then
    gpg --batch --yes --dearmor -o "$KEYRING" "$tmpkey" || fail "gpg --dearmor failed"
else
    install -m 0644 "$tmpkey" "$KEYRING"
fi
rm -f "$tmpkey"
chmod 0644 "$KEYRING"

# --- 4. apt source ----------------------------------------------------------
echo "[4/6] Registering the APT repository..."
echo "deb [signed-by=$KEYRING] $REPO_URL ./" > "$SOURCES"
chmod 0644 "$SOURCES"
apt-get update -qq -o Dir::Etc::sourcelist="$SOURCES" \
        -o Dir::Etc::sourceparts="-" -o APT::Get::List-Cleanup="0" \
    || fail "apt could not read $REPO_URL — repository unreachable or key rejected"
apt-get update -qq || echo "      (full apt update reported errors; continuing)"

# --- 5. SPLICE + a usable font ---------------------------------------------
echo "[5/6] Installing $PKG and its GTK/VTE dependencies..."
apt-get install -y "$PKG" || fail "apt could not install $PKG"

# A bare WSL rootfs often ships no fonts at all, which renders the terminal as
# a grid of empty boxes. Monospace is required; the emoji font is a nicety.
apt-get install -y -qq fonts-dejavu-core || echo "      (could not install fonts-dejavu-core)"
apt-get install -y -qq fonts-noto-color-emoji >/dev/null 2>&1 \
    || echo "      (emoji font unavailable — harmless)"

# --- 6. verify --------------------------------------------------------------
echo "[6/6] Verifying..."
command -v splice >/dev/null 2>&1 || fail "splice is not on PATH after install"
ver="$(dpkg-query -W -f='${Version}' "$PKG" 2>/dev/null || echo unknown)"

echo
echo "SPLICE $ver installed in ${WSL_DISTRO_NAME:-this distro}."
echo "Log: $LOG"
exit 0
