#!/bin/sh
set -e

# Simple local bring-up helper. Usage:
#   ./rad/scripts/local-up.sh
# It requires rad/.env.dev to exist (do NOT auto-create from examples) and then
# runs the prod+dev compose stack using COMPOSE_ENV to select the env file.

REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$REPO_ROOT"

if [ ! -f .env.dev ]; then
  echo ".env.dev not found. Create .env.dev with your development values (pointing to the external dev DB) and re-run."
  echo "You can copy .env.prod.example to start from a template, but DO NOT commit secrets."
  exit 1
fi

# Default to 'dev' but allow overriding with COMPOSE_ENV environment variable
COMPOSE_ENV=${COMPOSE_ENV:-dev}

echo "Starting compose with COMPOSE_ENV=$COMPOSE_ENV (using .env.$COMPOSE_ENV)"
# Load variables from .env.<env> into the environment so Compose variable
# substitution (e.g. ${NGINX_HTTP_PORT}) works. We export all variables from
# the file for the duration of the command.
ENV_FILE="$REPO_ROOT/.env.$COMPOSE_ENV"
if [ -f "$ENV_FILE" ]; then
  # Export variables from the .env file safely without sourcing it. Some
  # values include characters (parentheses, ampersands) that break POSIX
  # shell parsing if the file is sourced directly. Read line-by-line,
  # ignore comments/empty lines and export KEY=VALUE pairs.
  while IFS= read -r _line || [ -n "$_line" ]; do
    line="$_line"
    case "$line" in
      ''|\#*) continue ;;
    esac
    # Split on first '=' into key and value
    key=${line%%=*}
    val=${line#*=}
    # Export directly (preserves special characters in the value)
    export "$key=$val"
  done < "$ENV_FILE"
fi

COMPOSE_ENV=$COMPOSE_ENV docker compose -f docker/docker-compose.prod.yml -f docker/docker-compose.dev.yml up --build
