#!/bin/bash
# WEDA Desktop Icons — first-login setup.
#
# Runs via /etc/xdg/autostart/weda-desktop-setup.desktop at every GNOME
# login. Idempotent: tracks completion with a flag file and a log at
# ~/.cache/weda-desktop-icons-setup.log for diagnosing why icons didn't
# become trusted.

set -u

FLAG_FILE="$HOME/.config/weda-desktop-icons-setup.done"
LOG_FILE="$HOME/.cache/weda-desktop-icons-setup.log"
APPS_DIR="/usr/share/applications"
DESKTOP_DIR="$HOME/Desktop"

DESKTOP_FILES=(
    "weda-node.desktop"
    "weda-intro.desktop"
    "weda-learninghub.desktop"
)

mkdir -p "$(dirname "$LOG_FILE")"
exec >>"$LOG_FILE" 2>&1
echo "--- $(date -u '+%Y-%m-%dT%H:%M:%SZ') setup-desktop-icons.sh starting (uid=$(id -u), user=$(id -un)) ---"
echo "XDG_CURRENT_DESKTOP=${XDG_CURRENT_DESKTOP:-<unset>}"
echo "DBUS_SESSION_BUS_ADDRESS=${DBUS_SESSION_BUS_ADDRESS:-<unset>}"
echo "XDG_RUNTIME_DIR=${XDG_RUNTIME_DIR:-<unset>}"

# Already completed for this user — skip entirely.
if [ -f "$FLAG_FILE" ]; then
    echo "flag file exists, skipping"
    exit 0
fi

mkdir -p "$DESKTOP_DIR"

# Always do the copy + chmod half — those only need the filesystem.
# The gio half is best-effort and only runs when the session bus is ready.
copied=0
for f in "${DESKTOP_FILES[@]}"; do
    src="$APPS_DIR/$f"
    dst="$DESKTOP_DIR/$f"

    if [ ! -f "$src" ]; then
        echo "source missing: $src"
        continue
    fi

    if cp -f "$src" "$dst"; then
        chmod +x "$dst"
        echo "copied: $dst"
        copied=$((copied + 1))
    else
        echo "cp failed: $src -> $dst"
    fi
done

# Try to fix up DBUS_SESSION_BUS_ADDRESS if autostart fired before GNOME
# exported it into the environment. Use the session bus socket under
# /run/user/$UID which is the standard location for user buses.
if [ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ]; then
    uid=$(id -u)
    if [ -S "/run/user/${uid}/bus" ]; then
        export DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/${uid}/bus"
        echo "fixed up DBUS_SESSION_BUS_ADDRESS=$DBUS_SESSION_BUS_ADDRESS"
    fi
fi

trusted=0
if [ -n "${DBUS_SESSION_BUS_ADDRESS:-}" ] && command -v gio &>/dev/null; then
    for f in "${DESKTOP_FILES[@]}"; do
        dst="$DESKTOP_DIR/$f"
        [ -f "$dst" ] || continue
        if gio set "$dst" metadata::trusted true 2>&1; then
            echo "gio trusted: $dst"
            trusted=$((trusted + 1))
        else
            echo "gio set failed: $dst"
        fi
    done
else
    echo "skipping gio (bus=${DBUS_SESSION_BUS_ADDRESS:-<empty>}, gio=$(command -v gio || echo none))"
fi

echo "result: copied=$copied trusted=$trusted"

# Write flag only when BOTH halves succeeded so next login retries if
# the gio step was skipped (bus not ready, etc.).
if [ "$copied" -gt 0 ] && [ "$trusted" -ge "$copied" ]; then
    mkdir -p "$(dirname "$FLAG_FILE")"
    touch "$FLAG_FILE"
    echo "wrote flag file: $FLAG_FILE"
else
    echo "not writing flag (will retry on next login)"
fi
