#!/usr/bin/env bash
# wt-slot [--release]
# Give this worktree a stable slot on this machine and derive every runtime
# name from it: port, dev DB, test DB. Writes .env.wt (git-ignored).
# Main checkout = slot 0 = old defaults. Slots are leases in
# $WT_SLOT_DIR (default ~/.cache/wt-slots/<repo>), created with O_EXCL.
set -euo pipefail
top=$(git rev-parse --show-toplevel)
common=$(cd "$(git rev-parse --git-common-dir)" && pwd)
repo=$(basename "$(dirname "$common")")
machine=$(git config wt.machine || hostname -s)
tmpl=$(git config wt.dbtemplate || echo '{app}_{machine}_{slot}')
dir=${WT_SLOT_DIR:-$HOME/.cache/wt-slots/$repo}
mkdir -p "$dir"
[[ "$machine" =~ ^[a-z0-9]+$ ]] || { echo "wt-slot: wt.machine must be [a-z0-9]+, got '$machine'" >&2; exit 2; }

if [ ! -f "$top/.git" ]; then echo "wt-slot: main checkout uses slot 0 (defaults)"; exit 0; fi

slot=
for f in "$dir"/*.lease; do
  [ -e "$f" ] && [ "$(cat "$f")" = "$top" ] && slot=$(basename "$f" .lease)
done

if [ "${1:-}" = --release ]; then
  [ -n "$slot" ] || { echo "wt-slot: no slot held by $top"; exit 0; }
  [ -f "$top/.env.wt" ] && (cd "$top" && python - <<'PY'
from shop import wt; import django, os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "shop.settings"); django.setup()
from django.conf import settings; from shop import wt_db
sd = settings.DATABASES["default"]
for n in (settings.WT["WT_DB"], settings.WT["WT_TEST_DB"]): wt_db.release(n, settings.WT["WT_ID"], sd)
PY
  )
  rm -f "$dir/$slot.lease" "$top/.env.wt"; echo "wt-slot: released slot $slot"; exit 0
fi

if [ -z "$slot" ]; then
  for n in $(seq 1 ${WT_SLOT_MAX:-9}); do
    f="$dir/$n.lease"
    if [ -e "$f" ] && [ ! -d "$(cat "$f")" ]; then rm -f "$f"; fi       # holder worktree is gone
    if (set -C; echo "$top" > "$f") 2>/dev/null; then slot=$n; break; fi  # O_EXCL: one winner
  done
fi
[ -n "$slot" ] || { echo "wt-slot: all slots busy in $dir" >&2; exit 1; }

name() { local s=${tmpl//\{app\}/$1}; s=${s//\{machine\}/$machine}; echo "${s//\{slot\}/$slot}"; }
port=$(( ${WT_PORT_BASE:-8000} + 10 * slot ))
cat > "$top/.env.wt" <<ENV
# written by scripts/wt-slot; do not commit
WT_ID=$machine:$top
WT_SLOT=$slot
WT_PORT=$port
WT_DB=$(name shop)
WT_TEST_DB=$(name test_shop)
ENV
echo "wt-slot: $top -> slot $slot, port $port, db $(name shop), test db $(name test_shop)"
