#!/bin/sh
set -eu
repo_path="/cache/pikasTech/HWLAB.git"
mkdir -p "$repo_path/hooks"
cat > "$repo_path/hooks/pre-receive" <<'HOOK'
#!/bin/sh
set -eu
zero="0000000000000000000000000000000000000000"
status=0
while read -r old new ref; do
  if [ "$new" = "$zero" ]; then
    echo "git mirror write rejected: deleting $ref is forbidden" >&2
    status=1
    continue
  fi
  git cat-file -e "$new^{commit}" || status=1
  git cat-file -e "$new^{tree}" || status=1
  if git rev-list --objects --missing=print "$new" | grep -q '^?'; then
    echo "git mirror write rejected: missing objects for $new" >&2
    status=1
    continue
  fi
  if [ "$old" != "$zero" ] && ! git merge-base --is-ancestor "$old" "$new"; then
    echo "git mirror write rejected: non-fast-forward $ref" >&2
    status=1
    continue
  fi
done
exit "$status"
HOOK
cat > "$repo_path/hooks/post-receive" <<'HOOK'
#!/bin/sh
set -eu
repo_path=$(git rev-parse --git-dir)
git -C "$repo_path" update-server-info
written_at=$(date -u +%Y-%m-%dT%H:%M:%SZ)
export repo_path written_at
export gitops_branches_json=__HWLAB_GITOPS_BRANCHES_JSON_SHELL__
node - <<'NODE' > /cache/HWLAB.last-write.json
const { execFileSync } = require("node:child_process");
const repo = process.env.repo_path || "/cache/pikasTech/HWLAB.git";
const gitopsBranches = JSON.parse(process.env.gitops_branches_json || "[]");
function rev(ref) {
  try { return execFileSync("git", ["-C", repo, "rev-parse", ref], { encoding: "utf8" }).trim() || null; } catch { return null; }
}
const refs = {};
for (const branch of gitopsBranches) {
  refs["refs/heads/" + branch] = rev("refs/heads/" + branch);
  refs["refs/mirror-stage/heads/" + branch] = rev("refs/mirror-stage/heads/" + branch);
}
const pendingFlush = gitopsBranches.some((branch) => refs["refs/heads/" + branch] && refs["refs/heads/" + branch] !== refs["refs/mirror-stage/heads/" + branch]);
console.log(JSON.stringify({
  event: "git-mirror-write",
  status: "received",
  repository: "pikasTech/HWLAB",
  writtenAt: process.env.written_at,
  pendingFlush,
  refs
}));
NODE
HOOK
chmod 0755 "$repo_path/hooks/pre-receive" "$repo_path/hooks/post-receive"
git -C "$repo_path" config http.receivepack true
git -C "$repo_path" config receive.denyDeletes true
git -C "$repo_path" config receive.denyNonFastForwards true
