#!/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
}
# Git's fast-forward merge preserves unrelated local modifications and refuses
# to overwrite conflicting tracked or untracked files. Never delete local lock
# metadata or restore working files as a side effect of syncing.
if [[ -n "$("${git_cmd[@]}" status --porcelain)" ]]; then
    echo "Local changes detected; retaining them and checking for conflicts during fast-forward."
    "${git_cmd[@]}" status --short
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
