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

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

GOOSE_DRIVER="${GOOSE_DRIVER:-postgres}"
default_database_url="postgres://nomadcode:nomadcode@code-server-postgres:5432/nomadcode-core-local?sslmode=disable"
legacy_code_server_database_url="postgres://nomadcode:nomadcode@code-server-postgres:5432/nomadcode?sslmode=disable"
# code-server exports a shared DATABASE_URL; remap that default to this project's local DB.
if [[ "${DATABASE_URL:-}" == "$legacy_code_server_database_url" ]]; then
  DATABASE_URL="$default_database_url"
else
  DATABASE_URL="${DATABASE_URL:-$default_database_url}"
fi
GOOSE_DBSTRING="${GOOSE_DBSTRING:-$DATABASE_URL}"
if [[ "$GOOSE_DBSTRING" == "$legacy_code_server_database_url" ]]; then
  GOOSE_DBSTRING="$DATABASE_URL"
fi

if [[ -n "${GOOSE_BIN:-}" ]]; then
  goose_cmd=("$GOOSE_BIN")
else
  goose_cmd=(go run github.com/pressly/goose/v3/cmd/goose@v3.27.1)
fi

exec "${goose_cmd[@]}" -dir migrations "$GOOSE_DRIVER" "$GOOSE_DBSTRING" up
