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

log() { echo "[$(date -u +'%Y-%m-%dT%H:%M:%SZ')] $*"; }
fail() { echo "ERROR: $*" >&2; exit 1; }

# Env requirements
REQUIRED_VARS=(DB_HOST DB_PORT DB_NAME DB_USER DB_PASS)
for v in "${REQUIRED_VARS[@]}"; do : "${!v:?$v required}"; done

export PROJECT_DIR="${PROJECT_DIR:-/app}"
export FLASK_APP="${FLASK_APP:-${PROJECT_DIR}/scripts/run.py}"
export COMPONENT_NAME="${COMPONENT_NAME:-eveai_ops}"
export PYTHONPATH="${PYTHONPATH:-${PROJECT_DIR}:${PYTHONPATH-}}"

export PGPASSWORD="$DB_PASS"

log "Applying Alembic migrations to the tenant schemas (single run handling all tenants)..."
flask db upgrade -d "${PROJECT_DIR}/migrations/tenant"
log "Finished applying migrations to the tenant schemas."