#!/usr/bin/env bash
# 부모 timeline 에서 자식 timeline(branch) 을 만든다.
# 사용법: scripts/branch.sh <이름> [--at-lsn 0/16F9A00]
#   이름은 사람이 읽는 표시용이다. Neon 저장소 계층에는 timeline_id 만 있다.
#   --at-lsn 을 주면 과거 LSN 에서 분기한다(PITR 시나리오). 생략하면 부모의 현재 last_record_lsn 이다.
set -euo pipefail
cd "$(dirname "$0")/.."
PS=${PAGESERVER_URL:-http://localhost:9898}
NAME=${1:?branch name required}; shift || true
AT_LSN=""
while [[ $# -gt 0 ]]; do
  case "$1" in
    --at-lsn) AT_LSN="$2"; shift 2;;
    *) echo "unknown option $1"; exit 1;;
  esac
done
[[ -f .env ]] && source .env
: "${TENANT_ID:=$(curl -s "$PS/v1/tenant" | jq -r '.[0].id')}"
: "${TIMELINE_ID:=$(curl -s "$PS/v1/tenant/$TENANT_ID/timeline" | jq -r '[.[] | select(.ancestor_timeline_id == null)][0].timeline_id')}"
PARENT=${PARENT_TIMELINE_ID:-$TIMELINE_ID}
NEW_ID=$(python3 -c 'import secrets; print(secrets.token_hex(16))')
BODY=$(jq -cn --arg id "$NEW_ID" --arg anc "$PARENT" --arg lsn "$AT_LSN" --argjson pg "${PG_VERSION:-17}" \
  '{new_timeline_id:$id, ancestor_timeline_id:$anc, pg_version:$pg} + (if $lsn != "" then {ancestor_start_lsn:$lsn} else {} end)')
START=$(python3 -c 'import time; print(time.time())')
RESP=$(curl -s -w '\n%{http_code}' -X POST -H 'Content-Type: application/json' -d "$BODY" "$PS/v1/tenant/$TENANT_ID/timeline/")
CODE=$(tail -n1 <<<"$RESP"); JSON=$(sed '$d' <<<"$RESP")
END=$(python3 -c 'import time; print(time.time())')
if [[ "$CODE" != "201" ]]; then echo "create failed: HTTP $CODE"; echo "$JSON"; exit 1; fi
printf 'branch %s created in %.2fs\n' "$NAME" "$(python3 -c "print($END-$START)")"
echo "$JSON" | jq '{timeline_id, ancestor_timeline_id, ancestor_lsn, last_record_lsn, current_logical_size, current_physical_size}'
# .env 갱신: compose 가 compute1(TIMELINE_ID)과 compute2(BRANCH_TIMELINE_ID) 에 넘긴다
{
  echo "TENANT_ID=$TENANT_ID"
  echo "TIMELINE_ID=$TIMELINE_ID"
  echo "BRANCH_TIMELINE_ID=$NEW_ID"
  echo "PG_VERSION=${PG_VERSION:-17}"
} > .env
echo "$NAME $NEW_ID parent=$PARENT lsn=${AT_LSN:-head}" >> .branches
echo ".env updated: BRANCH_TIMELINE_ID=$NEW_ID"
echo "next: docker compose --profile branch up -d compute2   # 55434 포트"
