#!/usr/bin/env bash

# The Firefox chrome lands in the profile, on a machine that has never run
# Firefox.
#
# This is the one piece of Panama's configuration that does not go to a path the
# repository chooses. Firefox owns the profile directory, names it with a random
# salt, and does not create it until the browser has been run once -- so the
# usual "symlink config/dot/<name> to ~/.config/<name>" cannot reach it.
#
# Two things about that are easy to get wrong and were:
#
#   1. The profile root moved. A current Firefox keeps profiles under
#      ~/.config/mozilla/firefox and an older one under ~/.mozilla/firefox.
#      Writing to the wrong one silently themes nothing.
#   2. Both halves have to land. chrome/ holds the CSS, and user.js sets
#      toolkit.legacyUserProfileCustomizations.stylesheets -- without which
#      Firefox never reads chrome/ at all, and the theme is a directory of dead
#      files.
#
# So this runs link-dotfiles for real against a throwaway HOME with no profile in
# it, and looks at what came out. Nothing here touches the running machine.

set -uo pipefail

repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
theme_dir="$repo_dir/config/firefox"

findings=()
note() { findings+=("$1"); }

command -v firefox >/dev/null 2>&1 || {
    printf 'firefox chrome contract: firefox is not installed, so nothing was verified\n' >&2
    exit 0
}

# ── The theme is whole ───────────────────────────────────────────────────────

[[ -f "$theme_dir/user.js" ]] || note 'config/firefox has no user.js, so Firefox would ignore chrome/ entirely'
[[ -d "$theme_dir/chrome" ]] || note 'config/firefox has no chrome directory'
[[ -f "$theme_dir/README.md" ]] || note 'the vendored theme records no provenance or licence'

grep -q 'toolkit.legacyUserProfileCustomizations.stylesheets' "$theme_dir/user.js" 2>/dev/null \
    || note 'user.js does not enable userChrome.css, so none of the CSS is read'

# userChrome.css imports custom.css last so local changes need not touch the
# vendored files. The import resolving to nothing is legal CSS and therefore
# silent, which is exactly why it is worth checking.
if grep -q 'custom.css' "$theme_dir/chrome/userChrome.css" 2>/dev/null; then
    [[ -f "$theme_dir/chrome/custom.css" ]] \
        || note 'userChrome.css imports custom.css, which does not exist'
fi

# ── A real run, into a throwaway home ────────────────────────────────────────

fake_home="$(mktemp -d)"
trap 'rm -rf "$fake_home"' EXIT

HOME="$fake_home" XDG_CONFIG_HOME="$fake_home/.config" PANAMA_PATH="$repo_dir" \
    MOZ_HEADLESS=1 timeout 300 bash "$repo_dir/setup/scripts/link-dotfiles" >/dev/null 2>&1

profiles_ini="$(find "$fake_home" -name profiles.ini -print -quit 2>/dev/null)"
if [[ -z "$profiles_ini" ]]; then
    note 'no Firefox profile was created, so a fresh machine gets no chrome until the second install'
else
    root="$(dirname "$profiles_ini")"

    linked=0
    while read -r profile; do
        [[ -d "$profile" ]] || continue
        linked=1
        for piece in chrome user.js; do
            if [[ ! -e "$profile/$piece" ]]; then
                note "$piece never reached the profile at $(basename "$profile")"
            elif [[ ! -L "$profile/$piece" ]]; then
                note "$piece in the profile is not a link to the repository, so updates will not reach it"
            elif [[ "$(readlink -f "$profile/$piece")" != "$(readlink -f "$theme_dir/$piece")" ]]; then
                note "$piece in the profile points somewhere other than config/firefox"
            fi
        done
    done < <(awk -F= -v root="$root" '
        /^\[/          { relative = 1; next }
        /^IsRelative=/ { relative = $2; next }
        /^Path=/       { print (relative == 1 ? root "/" $2 : $2) }
    ' "$profiles_ini")

    (( linked == 1 )) || note 'profiles.ini lists no profile directory that exists'
fi

# ── Report ───────────────────────────────────────────────────────────────────

if (( ${#findings[@]} > 0 )); then
    mapfile -t findings < <(printf '%s\n' "${findings[@]}" | sort -u)
    printf 'firefox chrome contract: %d finding(s)\n' "${#findings[@]}" >&2
    printf '  - %s\n' "${findings[@]}" >&2
    exit 1
fi

printf 'firefox chrome contract: PASS\n'
