#!/usr/bin/env bash
# Run DB migrations in dependency order. Execute as cnperp user from /opt/cnperp.
set -euo pipefail

APP_DIR="${1:-/opt/cnperp}"
cd "$APP_DIR"
source .venv/bin/activate
export PYTHONPATH="$APP_DIR"
export PYTHONIOENCODING=utf-8

MIGRATION_PRIORITY=(
  add_company_multitenancy.py
  fix_user_email_nullable_unique.py
  add_licensing_tables.py
  add_license_key_encrypted.py
  add_branch_licenses_table.py
  add_cloud_sync_tables.py
  dedupe_walkin_customers.py
  prevent_duplicate_customers.py
)

run_one() {
  local base="$1"
  local path="migrations/${base}"
  if [[ ! -f "$path" ]]; then
    return 0
  fi
  echo "==> migration ${base}"
  python "$path" || {
    echo "WARN: ${base} failed (continuing)"
    return 0
  }
}

for base in "${MIGRATION_PRIORITY[@]}"; do
  run_one "$base"
done

for path in migrations/*.py; do
  [[ -f "$path" ]] || continue
  base=$(basename "$path")
  [[ "$base" == __* ]] && continue
  skip=0
  for p in "${MIGRATION_PRIORITY[@]}"; do
    if [[ "$base" == "$p" ]]; then
      skip=1
      break
    fi
  done
  [[ "$skip" -eq 1 ]] && continue
  run_one "$base"
done
