#!/usr/bin/env bash
# Keep the shared browsing checkout current after a successful deploy without ever
# disturbing active work in it. This is observability-only: every refusal is success.

main_checkout_ff_sync_json_quote() {
  local value=$1
  value=${value//\\/\\\\}
  value=${value//\"/\\\"}
  value=${value//$'\n'/\\n}
  value=${value//$'\r'/\\r}
  value=${value//$'\t'/\\t}
  printf '"%s"' "$value"
}

main_checkout_ff_sync() {
  local checkout=${OVERDECK_MAIN_CHECKOUT:-/home/user/Projects/overdeck}
  local state_dir=${OVERDECK_MAIN_CHECKOUT_SYNC_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/overdeck/main-checkout-sync}
  local log_file="$state_dir/attempts.jsonl"
  local status=refused blocking_path= detail= first_status

  MAIN_CHECKOUT_FF_SYNC_STATUS=unrecorded
  mkdir -p "$state_dir" 2>/dev/null || return 0

  if [[ -e "$checkout/.git/index.lock" ]]; then
    blocking_path=.git/index.lock
    detail=index-lock-present
  elif [[ ! -d "$checkout/.git" ]]; then
    blocking_path=.git
    detail=not-a-git-checkout
  elif ! first_status=$(/usr/bin/git -C "$checkout" status --porcelain --untracked-files=all 2>/dev/null); then
    blocking_path=.git
    detail=status-failed
  elif [[ -n "$first_status" ]]; then
    first_status=${first_status%%$'\n'*}
    blocking_path=${first_status:3}
    detail=dirty
  elif ! /usr/bin/git -C "$checkout" fetch origin --quiet 2>/dev/null; then
    blocking_path=.git/FETCH_HEAD
    detail=fetch-failed
  elif [[ -e "$checkout/.git/index.lock" ]]; then
    blocking_path=.git/index.lock
    detail=index-lock-present
  elif /usr/bin/git -C "$checkout" merge --ff-only origin/main >/dev/null 2>&1; then
    status=fast-forwarded
    detail=merged
  else
    blocking_path=.git/HEAD
    detail=diverged
  fi

  printf '{"step":"main-checkout-ff-sync","status":%s,"blocking_path":%s,"detail":%s}\n' \
    "$(main_checkout_ff_sync_json_quote "$status")" \
    "$(main_checkout_ff_sync_json_quote "$blocking_path")" \
    "$(main_checkout_ff_sync_json_quote "$detail")" >>"$log_file" 2>/dev/null || return 0
  MAIN_CHECKOUT_FF_SYNC_STATUS=$status
  return 0
}
