#!/usr/bin/env bash

set -euo pipefail

repo_root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
pages_worktree="$repo_root/.pages"

cd "$repo_root"

if ! command -v npm >/dev/null 2>&1; then
  echo "npm was not found in PATH." >&2
  echo "Install Node.js and npm, or add them to PATH before publishing docs." >&2
  exit 1
fi

npm run build:docs

rm -rf "$pages_worktree"
git fetch origin pages || true

if git show-ref --verify --quiet refs/remotes/origin/pages; then
  git worktree add --track -B pages "$pages_worktree" origin/pages
else
  git worktree add --detach "$pages_worktree"
  (
    cd "$pages_worktree"
    git checkout --orphan pages
  )
fi

find "$pages_worktree" -mindepth 1 -maxdepth 1 ! -name .git -exec rm -rf {} +
cp -R apps/docs/build/. "$pages_worktree/"

(
  cd "$pages_worktree"
  git add --all
  git diff --cached --quiet && exit 0
  git commit -m "Deploy docs for $(git -C "$repo_root" rev-parse --short HEAD)"
  git push origin HEAD:pages
)
