#!/usr/bin/env bash
# Fail-closed first: divergent or untracked content is never restored or discarded.
set -euo pipefail
signature=${1:?signature required}
[[ "$signature" =~ ^deploy-clone:([A-Za-z0-9][A-Za-z0-9._-]*)-dirty$ ]] || { echo "invalid deploy-clone signature: $signature" >&2; exit 2; }
deploy=${OVERDECK_DEPLOY_DIR:-$HOME/.local/share/overdeck/deploy}
[[ -d "$deploy/.git" ]] || { echo "deploy clone is missing: $deploy" >&2; exit 1; }
cd "$deploy"
/usr/bin/git fetch --quiet origin || { echo "cannot fetch origin/main for equivalence check" >&2; exit 1; }
mapfile -d '' status < <(/usr/bin/git status --porcelain=v1 -z --untracked-files=all)
[[ ${#status[@]} -gt 0 ]] || { echo "deploy clone is not dirty" >&2; exit 1; }
divergent=() restore=() remove=()
for entry in "${status[@]}"; do
  code=${entry:0:2} path=${entry:3}
  [[ "$path" != *" -> "* ]] || { divergent+=("$path"); continue; }
  if [[ "$code" == *D* ]]; then
    # A deletion of a tracked file never loses content — git holds it. Always restorable.
    restore+=("$path"); continue
  fi
  if /usr/bin/git cat-file -e "origin/main:$path" 2>/dev/null && /usr/bin/git show "origin/main:$path" | cmp -s - "$path"; then
    if [[ "$code" == '??' ]]; then remove+=("$path"); else restore+=("$path"); fi
  else
    divergent+=("$path")
  fi
done
if [[ ${#divergent[@]} -gt 0 ]]; then
  printf 'deploy clone has divergent local files; refusing to restore: %s\n' "${divergent[*]}" >&2
  exit 1
fi
# Per-file lossless restore only — never reset --hard: moving HEAD and rewriting the
# whole tree is the deploy's re-pin job, and reset does not even remove untracked
# files, so it can report success over a still-dirty clone. Every path below is
# proven recoverable (byte-identical in origin/main, or tracked content git holds).
[[ ${#restore[@]} -eq 0 ]] || /usr/bin/git restore --staged --worktree -- "${restore[@]}" \
  || { echo "cannot restore proven-equivalent files" >&2; exit 1; }
[[ ${#remove[@]} -eq 0 ]] || rm -f -- "${remove[@]}" \
  || { echo "cannot remove untracked byte-identical copies" >&2; exit 1; }
leftover="$(/usr/bin/git status --porcelain=v1 --untracked-files=all)" \
  && [[ -z "$leftover" ]] || { echo "clone still dirty after restore; escalating" >&2; exit 1; }
bash "$deploy/packaging/deploy-local.sh" || { echo "equivalent clone restored but deploy trigger failed" >&2; exit 1; }
printf '{"outcome":"shipped","detail":"Restored byte-identical deploy-clone state per file and queued a deploy.","proof":"every dirty file cmp -s origin/main or tracked-deletion; git restore per path; clean status verified; deploy-local.sh"}\n'
