#!/bin/bash
# deploy_pages.sh — push the built site/ to an orphan gitea-pages branch,
# matching the convention Gitea Pages serves from
# (pages.tourolle.paris/<owner>/<repo>/). Run scripts/docs/build_site.sh first.
#
# Uses a separate worktree so the main working tree / branch is untouched.
set -euo pipefail

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
cd "$REPO_ROOT"

if [ ! -d site ]; then
    echo "error: site/ not found — run scripts/docs/build_site.sh first" >&2
    exit 1
fi

WORKTREE="$(mktemp -d)"
trap 'rm -rf "$WORKTREE"' EXIT

if git show-ref --verify --quiet refs/remotes/origin/gitea-pages; then
    git worktree add -B gitea-pages "$WORKTREE" origin/gitea-pages
else
    git worktree add --orphan -B gitea-pages "$WORKTREE"
fi

# Replace the worktree's contents with the freshly built site.
find "$WORKTREE" -mindepth 1 -maxdepth 1 -not -name '.git' -exec rm -rf {} +
cp -r site/. "$WORKTREE/"
touch "$WORKTREE/.nojekyll"

cd "$WORKTREE"
git add -A
if git diff --cached --quiet; then
    echo "No changes to deploy (site is identical to the current gitea-pages branch)."
else
    git commit -m "docs: deploy from $(git -C "$REPO_ROOT" rev-parse --short HEAD)"
    git push origin gitea-pages:gitea-pages
    echo "Deployed. Should be live shortly at:"
    echo "  https://pages.tourolle.paris/dtourolle/scene-actor-extraction/"
fi

cd "$REPO_ROOT"
git worktree remove "$WORKTREE" --force 2>/dev/null || true
