#!/usr/bin/env bash
set -euo pipefail

COMPOSE_FILE=${COMPOSE_FILE:-/opt/bytelyst/learning_ai_devops_tools/deployments/open-notebook-pilot/docker-compose.yml}
ENV_FILE=${ENV_FILE:-/etc/bytelyst/open-notebook-pilot.env}
DATA_DIR=${DATA_DIR:-/opt/bytelyst/open-notebook-pilot}
BACKUP_DIR=${BACKUP_DIR:-$DATA_DIR/backups}
STAMP=${STAMP:-$(date -u +%Y%m%dT%H%M%SZ)}
OUT="$BACKUP_DIR/open-notebook-pilot-$STAMP.tar.gz"
META="$BACKUP_DIR/open-notebook-pilot-$STAMP.manifest.txt"

mkdir -p "$BACKUP_DIR"
chmod 700 "$BACKUP_DIR"

# Stop only the Open Notebook pilot to get a consistent RocksDB snapshot.
docker compose --env-file "$ENV_FILE" -f "$COMPOSE_FILE" stop open_notebook surrealdb >/dev/null

# Restart even if tar fails.
cleanup() {
  docker compose --env-file "$ENV_FILE" -f "$COMPOSE_FILE" up -d surrealdb open_notebook >/dev/null || true
}
trap cleanup EXIT

tar --warning=no-file-changed -C / -czf "$OUT" \
  opt/bytelyst/open-notebook-pilot/surreal_data \
  opt/bytelyst/open-notebook-pilot/notebook_data \
  etc/bytelyst/open-notebook-pilot.env
chmod 600 "$OUT"
sha256sum "$OUT" > "$META"
chmod 600 "$META"

printf 'backup=%s\nmanifest=%s\n' "$OUT" "$META"
