#!/usr/bin/env bash
# gobrr bootstrap — idempotent Nix + flake + darwin-rebuild for any
# Jesse-owned Mac.
#
# Canonical invocation (YubiKey-gated, hardware auth, no TLS deps):
#   ssh install@gobrr.lol | bash
#
# Fallback invocation (public HTTPS, for trust-less bootstrapping):
#   curl -sSL https://gobrr.lol | bash
#
# Override the leaf when hostname-user doesn't auto-derive:
#   GOBRR_LEAF=<leaf-name> <invocation above>
#
# If no <host>-<user> leaf matches, bootstrap falls back to `.#default`
# which is impure (uses $USER) but universal: works for any user.
#
# Truncation safety: the entire body lives inside main() and is only
# executed by the final line. If the curl/ssh stream is cut short,
# bash will exit on the unclosed function rather than running a
# partial sequence of side-effecting commands.

set -euo pipefail

# Pinned Determinate Nix installer. Bump both the URL tag and the
# sha256 together when upgrading. Verify a new release with:
#   curl -sSL https://install.determinate.systems/nix/tag/<TAG> \
#     | shasum -a 256
DET_NIX_URL="https://install.determinate.systems/nix/tag/v3.18.1"
DET_NIX_SHA256="fbf69e92ae8c70c49b07dbb507c566653d095acf31f9500170deed2cbcbfea16"

REMOTE_URL="ssh://git@go.gobrr.lol/srv/git/nix-config.git"
REPO="$HOME/nix-config"

main() {
    say() { printf '== %s ==\n' "$*"; }

    say "gobrr bootstrap"

    # 1. Nix (Determinate installer, version + sha pinned).
    if ! command -v nix >/dev/null 2>&1; then
        say "installing Nix (Determinate ${DET_NIX_URL##*/})"
        local tmp
        tmp="$(mktemp -t gobrr-det-nix.XXXXXX)"
        trap 'rm -f "$tmp"' RETURN
        curl --proto '=https' --tlsv1.2 -sSf -L "$DET_NIX_URL" -o "$tmp"
        printf '%s  %s\n' "$DET_NIX_SHA256" "$tmp" \
            | shasum -a 256 -c - >/dev/null \
            || { say "Determinate installer sha256 mismatch — refusing to run"; exit 1; }
        sh "$tmp" install --no-confirm
    fi
    if ! command -v nix >/dev/null 2>&1; then
        # shellcheck disable=SC1091
        . /nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh
    fi

    # 2. Clone or update the flake.
    if [ ! -d "$REPO/.git" ]; then
        say "cloning nix-config from gobrr"
        git clone "$REMOTE_URL" "$REPO"
        git -C "$REPO" remote rename origin gobrr
    else
        say "updating nix-config"
        if ! git -C "$REPO" remote get-url gobrr >/dev/null 2>&1; then
            git -C "$REPO" remote add gobrr "$REMOTE_URL"
        fi
        git -C "$REPO" fetch --quiet gobrr
        git -C "$REPO" pull --ff-only --quiet gobrr main
    fi

    cd "$REPO"

    # 3. Leaf: explicit override > hostname-user auto-derivation > default.
    local HOSTNAME_SHORT USER_LOWER LEAF IMPURE
    HOSTNAME_SHORT="$(scutil --get LocalHostName 2>/dev/null || hostname -s)"
    HOSTNAME_SHORT="$(printf '%s' "$HOSTNAME_SHORT" | tr 'A-Z' 'a-z')"
    USER_LOWER="$(printf '%s' "${USER:-$(whoami)}" | tr 'A-Z' 'a-z')"
    LEAF="${GOBRR_LEAF:-${HOSTNAME_SHORT}-${USER_LOWER}}"
    IMPURE=""

    if ! nix eval --raw ".#darwinConfigurations.${LEAF}.system.outPath" \
            >/dev/null 2>&1; then
        say "no leaf '${LEAF}' — falling back to .#default"
        LEAF="default"
        IMPURE="--impure"
        if ! nix eval --impure --raw \
                ".#darwinConfigurations.default.system.outPath" \
                >/dev/null 2>&1; then
            say "neither '${LEAF}' nor default evaluated — flake may be broken"
            echo "available leaves:"
            nix eval --json '.#darwinConfigurations' \
                    --apply 'builtins.attrNames' 2>/dev/null \
                | jq -r '.[]' | sed 's/^/    /'
            exit 1
        fi
    fi

    say "applying leaf .#${LEAF}${IMPURE:+ (impure)}"

    sudo darwin-rebuild switch --flake ".#${LEAF}" ${IMPURE}

    say "done — ${LEAF} applied from gobrr"
}

main "$@"
