#!/bin/bash
# uhhm-firefox-xdg: put Firefox in XDG mode AND move its profile onto
# machine-local storage (roam via Firefox Sync). Per user, idempotent.
# Firefox must be closed.
#
# On Firefox 155: legacy mode keeps everything under ~/.mozilla; XDG mode
# keeps everything (profile + the NFS-slow SQLite) under ~/.config/mozilla.
# Firefox uses legacy iff ~/.mozilla exists. Because ~/.config/mozilla is in
# the shared NFS home, the ONLY way to give each machine a fast local profile
# is to make it a symlink to a machine-local path — so every machine
# (identical path string, machine-local target) gets its own profile.
#
# The symlink is shared, so this applies to EVERY machine using the home;
# uhhm-session-init creates the local profile dir on the others at login.
set -euo pipefail
. /usr/lib/uhhm/uhhm-lib.sh

xdg_moz="${XDG_CONFIG_HOME:-$HOME/.config}/mozilla"
legacy="$HOME/.mozilla"

if pgrep -u "$(id -un)" -x firefox >/dev/null 2>&1; then
    echo "Close Firefox first." >&2; exit 1
fi

mkdir -p "$(dirname "$xdg_moz")"
uhhm_moz_ensure
local_moz=$(uhhm_moz_local)

# Seed the machine-local store once from whatever profile exists, then get the
# in-home copies out of the way so XDG mode + the symlink take effect. A failed
# copy aborts (set -e) BEFORE the original is moved aside.
if [ -e "$legacy" ] && [ ! -L "$legacy" ]; then
    echo "migrating legacy ~/.mozilla -> $local_moz ..."
    cp -a "$legacy/." "$local_moz/"
    mv "$legacy" "${legacy}.pre-xdg-$(date +%s)"
fi
if [ -e "$xdg_moz" ] && [ ! -L "$xdg_moz" ]; then
    echo "migrating ~/.config/mozilla -> $local_moz ..."
    cp -a "$xdg_moz/." "$local_moz/"
    mv "$xdg_moz" "${xdg_moz}.pre-local-$(date +%s)"
fi

[ -L "$xdg_moz" ] || ln -sfn "$local_moz" "$xdg_moz"

echo "Firefox now runs in XDG mode with a machine-local profile:"
echo "  ~/.config/mozilla -> $local_moz"
echo "This applies on every machine sharing this home (each gets its own profile)."
echo "Sign into Firefox Sync to roam bookmarks/history/prefs across machines."
