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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
cd "$ROOT_DIR"

DRY_RUN=1
APPLY=0
PROBE_PORTS=""

usage() {
  cat <<'USAGE'
Usage:
  bash scripts/docs/services_sync.sh [--dry-run] [--apply] [--probe-ports 39300,39301]

Workflow:
  1) docs backup
  2) integration bootstrap status
  3) jupyter sync adapter
  4) pieces sync adapter
USAGE
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --dry-run)
      DRY_RUN=1
      APPLY=0
      shift
      ;;
    --apply)
      APPLY=1
      DRY_RUN=0
      shift
      ;;
    --probe-ports)
      PROBE_PORTS="$2"
      shift 2
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown arg: $1" >&2
      usage
      exit 2
      ;;
  esac
done

if [[ "$DRY_RUN" -eq 1 ]]; then
  echo "[dry-run] running: scripts/docs/docs_backup.sh --dry-run"
  bash scripts/docs/docs_backup.sh --dry-run
  echo "[dry-run] running: scripts/docs/session_bootstrap.sh"
  bash scripts/docs/session_bootstrap.sh
  echo "[dry-run] running: scripts/docs/jupyter_sync.sh --dry-run"
  bash scripts/docs/jupyter_sync.sh --dry-run
  echo "[dry-run] running: scripts/docs/pieces_sync.sh --dry-run"
  if [[ -n "$PROBE_PORTS" ]]; then
    bash scripts/docs/pieces_sync.sh --dry-run --probe-ports "$PROBE_PORTS"
  else
    bash scripts/docs/pieces_sync.sh --dry-run
  fi
  exit 0
fi

bash scripts/docs/docs_backup.sh --apply
bash scripts/docs/session_bootstrap.sh
bash scripts/docs/jupyter_sync.sh --apply
if [[ -n "$PROBE_PORTS" ]]; then
  bash scripts/docs/pieces_sync.sh --apply --probe-ports "$PROBE_PORTS"
else
  bash scripts/docs/pieces_sync.sh --apply
fi

echo "services sync completed"
