#!/bin/bash
set -u

TRUST_DEPTH=5
TRUST_REF="refs/remotes/origin/master"
GATE_PRECOMMIT_SRC=".dev-config/hooks/pre-commit"
GATE_REFERENCE_SRC=".dev-config/hooks/reference-transaction"
GATE_HELPER_SRC=".dev-config/bin/ipz-remote-php-gate"

# Print the blob OIDs of $1 across the last TRUST_DEPTH landed versions on TRUST_REF.
trusted_blobs_for_path() {
    local path=$1 commit blob
    git rev-list -n "$TRUST_DEPTH" "$TRUST_REF" -- "$path" 2>/dev/null |
    while read -r commit; do
        blob=$(git rev-parse -q --verify "$commit:$path" 2>/dev/null) || continue
        printf '%s\n' "$blob"
    done
}

# Installed file $1 must byte-match some landed version of source path $2.
installed_blob_is_trusted() {
    local active=$1 tracked=$2 active_oid blob matched=1
    active_oid=$(git hash-object --no-filters "$active" 2>/dev/null) || return 1
    while read -r blob; do
        [ -n "$blob" ] && [ "$active_oid" = "$blob" ] && matched=0
    done < <(trusted_blobs_for_path "$tracked")
    return "$matched"
}

usage() {
    printf 'Usage: %s [--from-head] [--gc]\n' "$0" >&2
}

fail() {
    printf 'install-ipz-gate: %s\n' "$*" >&2
    exit 1
}

current_uid=$(id -u)

check_directory() {
    local dir=$1 expected_mode=$2

    [ -d "$dir" ] && [ ! -L "$dir" ] || return 1
    [ "$(realpath -e "$dir" 2>/dev/null)" = "$dir" ] || return 1
    [ "$(stat -c '%u' "$dir" 2>/dev/null)" = "$current_uid" ] || return 1
    [ "$(stat -c '%a' "$dir" 2>/dev/null)" = "$expected_mode" ] || return 1
}

check_installed_file() {
    local file=$1 expected_blob=$2

    [ -f "$file" ] && [ ! -L "$file" ] || return 1
    [ "$(realpath -e "$file" 2>/dev/null)" = "$file" ] || return 1
    [ "$(stat -c '%u' "$file" 2>/dev/null)" = "$current_uid" ] || return 1
    [ "$(stat -c '%a' "$file" 2>/dev/null)" = '500' ] || return 1
    [ "$(git hash-object --no-filters "$file" 2>/dev/null)" = "$expected_blob" ] || return 1
}

validate_existing_install() {
    local dir=$1 i file

    check_directory "$dir" 500 || return 1
    for i in "${!paths[@]}"; do
        file="$dir/${paths[$i]##*/}"
        check_installed_file "$file" "${blobs[$i]}" || return 1
    done
}

from_head=0
gc=0
for arg in "$@"; do
    case "$arg" in
        --from-head) from_head=1 ;;
        --gc) gc=1 ;;
        --help|-h)
            usage
            exit 0
            ;;
        *)
            usage
            fail "unknown option: $arg"
            ;;
    esac
done

common_dir=$(git rev-parse --git-common-dir 2>/dev/null) || fail 'unable to determine the shared Git directory'
common=$(realpath "$common_dir" 2>/dev/null) || fail 'unable to resolve the shared Git directory'
repo_root=$(git rev-parse --show-toplevel 2>/dev/null) || fail 'unable to determine the repository root'
repo_root=$(realpath "$repo_root" 2>/dev/null) || fail 'unable to resolve the repository root'

source_ref=$TRUST_REF
if [ "$from_head" -eq 1 ]; then
    source_ref=HEAD
    printf 'WARNING: installing gate sources from HEAD; --from-head is for bootstrap/development only.\n' >&2
fi

paths=("$GATE_PRECOMMIT_SRC" "$GATE_REFERENCE_SRC" "$GATE_HELPER_SRC")
blobs=()
for path in "${paths[@]}"; do
    blob=$(git rev-parse -q --verify "$source_ref:$path" 2>/dev/null) || fail "missing $path on $source_ref"
    blobs+=("$blob")
done

digest=$(printf '%s\n' "${blobs[@]}" | sha256sum) || fail 'unable to calculate install version'
[[ "$digest" =~ ^[0-9a-f]{64}[[:space:]] ]] || fail 'invalid install version digest'
version_id=${digest:0:12}
top="$common/ipz-remote-gate-hooks"
if [ -e "$top" ] || [ -L "$top" ]; then
    check_directory "$top" 700 || fail "existing gate top directory is not a trusted owner-only directory: $top"
else
    mkdir "$top" || fail "unable to create $top"
    chmod 700 "$top" || fail "unable to secure $top"
    check_directory "$top" 700 || fail "created gate top directory is not a trusted owner-only directory: $top"
fi
install_dir="$top/$version_id"

if [ -e "$install_dir" ] || [ -L "$install_dir" ]; then
    validate_existing_install "$install_dir" || fail "existing gate installation is incomplete, corrupt, or untrusted: $install_dir"
else
    tmp=$(mktemp -d "$top/.install.XXXXXX") || fail "unable to create a temporary install directory"
    cleanup_tmp=1
    cleanup() {
        [ "${cleanup_tmp:-0}" -eq 1 ] && rm -rf "$tmp"
    }
    trap cleanup EXIT HUP INT TERM

    for i in "${!paths[@]}"; do
        git cat-file blob "${blobs[$i]}" > "$tmp/${paths[$i]##*/}" || fail "unable to materialize ${paths[$i]}"
        chmod 500 "$tmp/${paths[$i]##*/}" || fail "unable to secure ${paths[$i]}"
    done
    chmod 500 "$tmp" || fail "unable to secure install directory"

    if mv -T "$tmp" "$install_dir"; then
        cleanup_tmp=0
    elif [ -e "$install_dir" ] || [ -L "$install_dir" ]; then
        rm -rf "$tmp"
        cleanup_tmp=0
        validate_existing_install "$install_dir" || fail "concurrent gate installation is incomplete, corrupt, or untrusted: $install_dir"
    else
        fail "unable to install $install_dir"
    fi
    trap - EXIT HUP INT TERM

    validate_existing_install "$install_dir" || fail "created gate installation is incomplete, corrupt, or untrusted: $install_dir"
fi

git config extensions.worktreeConfig true || fail 'unable to enable worktree configuration'
git config --worktree core.hooksPath "$install_dir" || fail 'unable to pin this worktree to the installed gate'

printf 'Installed gate version: %s\n' "$version_id"
printf 'Install path: %s\n' "$install_dir"
printf 'Pinned worktree: %s\n' "$repo_root"

if [ "$gc" -eq 1 ]; then
    printf 'Gate install garbage collection is not implemented.\n'
fi
