#!/usr/bin/env bash

set -euo pipefail

repository_root="$(git rev-parse --show-toplevel && printf '.')"
repository_root="${repository_root%.}"
repository_root="${repository_root%$'\n'}"
CDPATH= cd "$repository_root"

if git rev-parse --verify MERGE_HEAD >/dev/null 2>&1; then
    exec .githooks/pre-merge-commit
fi

primary="$(scripts/detect-primary-branch.sh)"
current="$(git branch --show-current)"

if [[ "$current" == "$primary" ]]; then
    printf 'Direct commits on primary are not allowed: %s\n' "$primary" >&2
    exit 1
fi

profile="$(.venv/bin/python scripts/check_change_scope.py --index --base HEAD)"
case "$profile" in
    documentation)
        exec .venv/bin/python scripts/check-docs.py --index --base HEAD
        ;;
    full)
        exec scripts/check-fast.sh
        ;;
    *)
        printf 'Unrecognized check profile: %s\n' "$profile" >&2
        exit 1
        ;;
esac
