#!/usr/bin/env bash
# takeal-release — deploy-kit rollout for boxes WITHOUT a git checkout (#60).
#
#   takeal-release <tag>        # e.g. takeal-release v0.1.2
#   takeal-release --rollback   # previous tag again (already on disk)
#
# Layout under TAKEAL_KIT_ROOT (default /opt/takeal):
#   .env                     the box's secrets (0600) — never inside a release
#   okcard-data/ backups/    connector state, tkli dumps — survive releases
#   releases/<tag>/deploy/   one unpacked kit per tag (compose, Caddyfile, …)
#   current -> releases/<tag>
#
# The kit is `takeal-deploy-<tag>.tar.gz`, attached to the Forgejo release of
# the tag by the CI workflow. It is fetched with DEPLOY_TOKEN from .env — the
# pull-only bot token (packages:read + release download), the same one used
# for `docker login`. Nothing with source access ever lands on the box.
#
# Install once: copy this file to /usr/local/bin/takeal-release (it is also
# inside every kit at deploy/kit/takeal-release; the kit's own copy is used
# from then on via `current/deploy/kit/takeal-release`).
set -euo pipefail

KIT_ROOT="${TAKEAL_KIT_ROOT:-/opt/takeal}"
API="${TAKEAL_FORGEJO_API:-https://git.wiseless.xyz/api/v1/repos/takeal/takeal}"
ENVF="$KIT_ROOT/.env"
die() { echo "!! $*" >&2; exit 1; }

[ -f "$ENVF" ] || die "no $ENVF — create it from deploy/.env.prod.example (inside any kit)"
MODE="${1:?usage: takeal-release <tag> | --rollback}"

if [ "$MODE" = "--rollback" ]; then
  PREV="$(cat "$KIT_ROOT/.release-prev" 2>/dev/null || true)"
  [ -n "$PREV" ] || die "no previous release recorded in $KIT_ROOT/.release-prev"
  [ -x "$KIT_ROOT/releases/$PREV/deploy/release.sh" ] || die "kit for $PREV is not on disk"
  exec env TAKEAL_KIT_ROOT="$KIT_ROOT" "$KIT_ROOT/releases/$PREV/deploy/release.sh" --kit --rollback
fi

TAG="$MODE"
DIR="$KIT_ROOT/releases/$TAG"
if [ ! -x "$DIR/deploy/release.sh" ]; then
  TOKEN="$(grep -E '^DEPLOY_TOKEN=' "$ENVF" | tail -1 | cut -d= -f2-)"
  [ -n "$TOKEN" ] || die "DEPLOY_TOKEN is empty in $ENVF (pull-only bot token)"
  KIT="takeal-deploy-$TAG.tar.gz"
  echo "=== fetching $KIT"
  URL="$(curl -sf -H "Authorization: token $TOKEN" "$API/releases/tags/$TAG" \
         | python3 -c 'import json,sys
name=sys.argv[1]
for a in json.load(sys.stdin).get("assets",[]):
    if a["name"]==name: print(a["browser_download_url"]); break' "$KIT")" || die "release $TAG not found (or DEPLOY_TOKEN lacks access)"
  [ -n "$URL" ] || die "release $TAG has no $KIT asset — was the CI workflow run for this tag?"
  TMP="$(mktemp -d)"; trap 'rm -rf "$TMP"' EXIT
  curl -sfL -H "Authorization: token $TOKEN" -o "$TMP/$KIT" "$URL" || die "download failed"
  mkdir -p "$DIR"
  tar xzf "$TMP/$KIT" -C "$DIR"
  [ -x "$DIR/deploy/release.sh" ] || chmod +x "$DIR/deploy/release.sh" "$DIR"/deploy/backup/*.sh "$DIR"/deploy/kit/* 2>/dev/null || true
  echo "=== unpacked to $DIR"
fi

exec env TAKEAL_KIT_ROOT="$KIT_ROOT" "$DIR/deploy/release.sh" --kit "$TAG"
