#!/bin/sh
# Generate a wallpaper with machine identity overlaid.
# Safe to run on first boot; caches result in project-local tmp/ when a project
# root is available, otherwise in the live user's app-owned cache directory.
# Requires ImageMagick (magick or convert). Tailscale is optional.

CLAWDIE_BG="/usr/local/share/clawdie-iso/wallpapers/clawdie-operator-bg.png"
XFCE_BG="/usr/local/share/backgrounds/xfce/default.png"

have() {
    command -v "$1" >/dev/null 2>&1
}

project_root() {
    if [ -n "${CLAWDIE_PROJECT_ROOT:-}" ]; then
        printf '%s\n' "$CLAWDIE_PROJECT_ROOT"
    elif have git && git rev-parse --show-toplevel >/dev/null 2>&1; then
        git rev-parse --show-toplevel
    else
        return 1
    fi
}

scratch_dir() {
    if [ -n "${CLAWDIE_TMP:-}" ]; then
        printf '%s\n' "$CLAWDIE_TMP"
    elif _root=$(project_root); then
        printf '%s/tmp\n' "$_root"
    elif [ -n "${XDG_CACHE_HOME:-}" ]; then
        printf '%s/clawdie\n' "$XDG_CACHE_HOME"
    elif [ -n "${HOME:-}" ]; then
        printf '%s/.cache/clawdie\n' "$HOME"
    else
        printf '%s\n' "/var/cache/clawdie"
    fi
}

if have magick; then
    im() { magick "$@"; }
elif have convert; then
    im() { convert "$@"; }
else
    echo "ERROR: ImageMagick is not installed; expected magick or convert." >&2
    exit 1
fi

SCRATCH_DIR=$(scratch_dir)
mkdir -p "$SCRATCH_DIR"
OUT="${1:-${SCRATCH_DIR}/clawdie-wallpaper.png}"
FALLBACK_BG="${SCRATCH_DIR}/clawdie-wallpaper-base.png"

HOST=$(hostname 2>/dev/null || echo "clawdie-live")
if have tailscale; then
    TS_IP=$(tailscale ip -4 2>/dev/null | head -n 1)
fi
[ -n "${TS_IP:-}" ] || TS_IP="offline"
COLIBRI_SOCK="/var/run/colibri/colibri.sock"
COLIBRI_PORT="9190"
JAIL_RELEASE=$(freebsd-version 2>/dev/null || uname -r 2>/dev/null || echo "unknown")

if [ -f "$CLAWDIE_BG" ]; then
    BG="$CLAWDIE_BG"
elif [ -f "$XFCE_BG" ]; then
    BG="$XFCE_BG"
else
    BG="$FALLBACK_BG"
    im -size 1920x1080 xc:'#1a1a2e' "$BG"
fi

SOCK_STATUS="down"
[ -S "$COLIBRI_SOCK" ] && SOCK_STATUS="socket ${COLIBRI_PORT}"

# Overlay identity text in the bottom-left corner. Do not require a specific
# font: ImageMagick's default font is more portable across FreeBSD package sets.
if ! im "$BG" \
    -pointsize 18 -fill '#e0e0e0' \
    -annotate +40+900 "hostname    ${HOST}" \
    -annotate +40+930 "tailscale   ${TS_IP}" \
    -annotate +40+960 "colibri     ${SOCK_STATUS}" \
    -annotate +40+990 "jail        ${JAIL_RELEASE}" \
    -pointsize 28 -fill '#8b5cf6' \
    -annotate +40+850 "Clawdie OS" \
    "$OUT"; then
    echo "WARNING: identity overlay failed; copying base wallpaper instead." >&2
    cp "$BG" "$OUT"
fi

# stdout is the bare output path (machine-readable for callers that capture it,
# e.g. `WP=$(clawdie-wallpaper-gen)`); human-facing note goes to stderr.
echo "Wallpaper: ${OUT}" >&2
printf '%s\n' "$OUT"
