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

repo_root="${JEANNIE_SERVER_REPO_ROOT:-${REPO_ROOT:-$(pwd)}}"
remote="${JEANNIE_REPO_SYNC_REMOTE:-origin}"
branch="${JEANNIE_REPO_SYNC_BRANCH:-}"

while (($# > 0)); do
    case "$1" in
        --remote) remote="${2:-}"; shift 2 ;;
        --branch) branch="${2:-}"; shift 2 ;;
        *) echo "Usage: ./jeannie repo-sync [--remote REMOTE] [--branch BRANCH]" >&2; exit 2 ;;
    esac
done

[[ -d "${repo_root}/.git" ]] || { echo "Git repository not found: ${repo_root}" >&2; exit 1; }
git_cmd=(git -C "${repo_root}")
current_branch="$("${git_cmd[@]}" branch --show-current)"
[[ -n "${branch}" ]] || branch="${current_branch}"
[[ -n "${branch}" ]] || { echo "Repository is in detached HEAD; specify --branch." >&2; exit 2; }
"${git_cmd[@]}" remote get-url "${remote}" >/dev/null || {
    echo "Git remote not found: ${remote}" >&2
    exit 2
}
# OpenTofu leaves this transient lock metadata after an interrupted plan. It
# is safe to remove only when no OpenTofu process is still running; real source
# changes remain blocking as before.
stale_tofu_lock="${repo_root}/bootstrap/oci/.terraform.tfstate.lock.info"
if [[ -f "${stale_tofu_lock}" ]] && ! pgrep -af '[t]ofu' >/dev/null 2>&1; then
    rm -f "${stale_tofu_lock}"
    echo "Removed stale OpenTofu lock metadata: ${stale_tofu_lock}"
fi
if [[ -n "$("${git_cmd[@]}" status --porcelain)" ]]; then
    echo "Refusing repo sync: working tree is not clean." >&2
    "${git_cmd[@]}" status --short >&2
    exit 1
fi

before="$("${git_cmd[@]}" rev-parse HEAD)"
printf 'Repository: %s\nRemote: %s\nBranch: %s\nBefore: %s\n' "${repo_root}" "${remote}" "${branch}" "${before}"
"${git_cmd[@]}" fetch --prune "${remote}" "${branch}"
remote_ref="${remote}/${branch}"
"${git_cmd[@]}" rev-parse --verify "${remote_ref}" >/dev/null || {
    echo "Remote branch not found: ${remote_ref}" >&2
    exit 1
}
"${git_cmd[@]}" merge --ff-only "${remote_ref}"
after="$("${git_cmd[@]}" rev-parse HEAD)"
if [[ "${before}" == "${after}" ]]; then
    echo "Already up to date."
else
    printf 'Updated: %s -> %s\n' "${before}" "${after}"
fi
