#!/usr/bin/env bash
set -Eeuo pipefail
BASE=/home/dunedeploy/ci-deploy
REPO=/home/dunedeploy/web-deployment
SOURCE_URL=https://www.dunerealms.com/git/unimatrix/web.git
# Share the publication mutex; no cleanup command is part of a build.
exec 9< /mnt/HC_Volume_107481500/dunegit/ci/promotion/safe-lock
flock --shared --nonblock 9 || { echo 'Publication mutex busy; build deferred to systemd retry'; exit 75; }
SHA=$(cat "$BASE/pending-commit")
[[ "$SHA" =~ ^[0-9a-f]{40}$ ]] || exit 1
cd "$REPO"
git fetch -q "$SOURCE_URL" refs/heads/main
MAIN=$(git rev-parse FETCH_HEAD)
[[ "$SHA" == "$MAIN" ]] || { echo 'Not current main'; exit 1; }
DEST="$BASE/artifacts/$SHA"
TMP="$BASE/artifacts/.${SHA}.tmp.$$"
trap 'rm -rf "$TMP"' EXIT
mkdir -p "$TMP"
git archive "$SHA" website tools .forgejo | tar -x -C "$TMP"
cd "$TMP/website"
corepack pnpm install --frozen-lockfile
corepack pnpm build
corepack pnpm test
[[ -f dist/server/index.js ]] || { echo 'Missing server build'; exit 1; }
python3 - "$SHA" "$TMP" <<'PY'
import json,pathlib,sys,time
(pathlib.Path(sys.argv[2])/'.staging-complete.json').write_text(json.dumps({'version':1,'sha':sys.argv[1],'completedAt':time.time()}))
PY
if [[ ! -d "$DEST" ]]; then mv "$TMP" "$DEST"; fi
printf '%s\n' "$SHA" > "$BASE/built-commit.tmp"
mv -f "$BASE/built-commit.tmp" "$BASE/built-commit"
echo "Built CI release: $SHA; production unchanged"
