#!/usr/bin/env bash
# Bash translation of the repo's scripts/bootstrap.ps1 -StartServices
# (bootstrap + migrate). Run from the repository root.
set -euo pipefail
COMPOSE=(docker compose --env-file .env -f deploy/local/compose.yaml)

if [ ! -f .env ]; then
  sed "s/replace-with-a-local-secret/$(uuidgen | tr -d - | tr 'A-Z' 'a-z')/" .env.example > .env
  echo "Created .env with a generated local database password."
fi

"${COMPOSE[@]}" config --quiet
"${COMPOSE[@]}" up -d --build --wait

for f in $(ls migrations/*.up.sql | sort); do
  v=$((10#$(basename "$f" | grep -Eo '^[0-9]+')))
  applied=0
  ledger=$("${COMPOSE[@]}" exec -T postgres psql -At -U durable -d durable -c \
    "SELECT to_regclass('engine.schema_migrations') IS NOT NULL")
  if [ "$ledger" = "t" ]; then
    applied=$("${COMPOSE[@]}" exec -T postgres psql -At -U durable -d durable -c \
      "SELECT count(*) FROM engine.schema_migrations WHERE version = $v")
  fi
  if [ "$applied" = "1" ]; then echo "skip  $(basename "$f")"; continue; fi
  echo "apply $(basename "$f")"
  "${COMPOSE[@]}" exec -T postgres psql -q -v ON_ERROR_STOP=1 -U durable -d durable < "$f" >/dev/null
done
"${COMPOSE[@]}" ps --format 'table {{.Service}}\t{{.Status}}'
