#!/usr/bin/env bash
set -euo pipefail

base_ref="${1:-}"

if [[ -z "${base_ref}" ]]; then
    base_ref="$(
        python3 - <<'PY'
import json
import os

path = os.environ.get("GITHUB_EVENT_PATH", "")
if path and os.path.exists(path):
    with open(path, encoding="utf-8") as handle:
        print(json.load(handle).get("before", ""))
PY
    )"
fi

if [[ -z "${base_ref}" || "${base_ref}" =~ ^0+$ ]]; then
    base_ref="$(git rev-parse HEAD^ 2>/dev/null || git hash-object -t tree /dev/null)"
fi

changed_files="$(git diff --name-only "${base_ref}" HEAD)"

mode="k8s-update"
while IFS= read -r path; do
    [[ -n "${path}" ]] || continue
    case "${path}" in
        .gitea/workflows/* | \
        bootstrap/apps/* | \
        bootstrap/cluster/* | \
        bootstrap/edge/* | \
        bootstrap/host/* | \
        bootstrap/platform/* | \
        bootstrap/provisioning/* | \
        homelab.yml | \
        infra/gitea/* | \
        jeannie | \
        lib/jeannie/* | \
        scripts/*)
            mode="debian-ops"
            break
            ;;
    esac
done <<<"${changed_files}"

printf 'mode=%s\n' "${mode}"
printf 'base_ref=%s\n' "${base_ref}"
printf '%s\n' "${changed_files}" | sed '/^$/d'
