#!/usr/bin/env bash

set -euo pipefail

REPO_ROOT="$(git rev-parse --show-toplevel 2>/dev/null || true)"
LOCK_FILE=".context.lock"

if [[ -z "$REPO_ROOT" ]]; then
  echo "Not inside a git repository" >&2
  exit 1
fi

if [[ "$(pwd)" != "$REPO_ROOT" ]]; then
  echo "Run this script from the repo root" >&2
  exit 1
fi

mapfile -t status_lines < <(git status --porcelain=v1 --untracked-files=all)

for line in "${status_lines[@]}"; do
  path="${line:3}"
  if [[ "$path" != "codex_context.yaml" ]]; then
    echo "Refusing to sync: only codex_context.yaml may be changed" >&2
    exit 1
  fi
done

git pull --rebase

if git diff --quiet -- codex_context.yaml && git diff --cached --quiet -- codex_context.yaml; then
  echo "No context changes to sync"
  exit 0
fi

if [[ -e "$LOCK_FILE" ]]; then
  echo "Shared context is locked:" >&2
  cat "$LOCK_FILE" >&2
  exit 1
fi

lock_created=0

cleanup_note() {
  if [[ "$lock_created" -eq 1 ]]; then
    echo "Lock may need manual cleanup" >&2
  fi
}

trap cleanup_note ERR

printf "hostname: %s\nusername: %s\ntimestamp: %s\n" \
  "$(hostname)" \
  "$(id -un)" \
  "$(date -u +"%Y-%m-%dT%H:%M:%SZ")" \
  > "$LOCK_FILE"
lock_created=1
git add "$LOCK_FILE"
git commit -m "lock shared context"
git push

python3 -c "import yaml; yaml.safe_load(open('codex_context.yaml'))"
git add codex_context.yaml
git commit -m "update shared context"
git push

rm -f "$LOCK_FILE"
git add "$LOCK_FILE"
git commit -m "unlock shared context"
git push
trap - ERR
