#!/bin/sh
set -e

# Simple local bring-up helper. Usage:
#   ./rad/scripts/local-up.sh [--no-build]
#
# Options:
#   -n, --no-build   Skip rebuilding images (omit `--build` when bringing up compose)
#   -h, --help       Show this help message
#
# 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

# Parse simple CLI flags. Use --no-build or -n to skip rebuilding docker images.
NO_BUILD=0
while [ "$#" -gt 0 ]; do
  case "$1" in
    -n|--no-build)
      NO_BUILD=1
      shift
      ;;
    -h|--help)
      sed -n '1,40p' "$0"
      exit 0
      ;;
    *)
      echo "Unknown option: $1"
      echo "Run with --help to see available options."
      exit 1
      ;;
  esac
done

# 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

# Ensure runtime directories exist for Loki and nginx logs so compose startup
# doesn't fail with permission/missing-folder errors. We create the minimal
# subfolders Loki expects and a host `logs/` for nginx/Promtail.
echo "Ensuring loki and logs folders exist under $REPO_ROOT/docker and $REPO_ROOT/logs"
mkdir -p "$REPO_ROOT/docker/loki-data/index" \
         "$REPO_ROOT/docker/loki-data/cache" \
         "$REPO_ROOT/docker/loki-data/chunks" \
         "$REPO_ROOT/docker/loki-data/compactor" \
         "$REPO_ROOT/docker/loki-wal" \
         "$REPO_ROOT/logs"

# Set permissive perms for logs so nginx/promtail can use it in development.
# Only change permissions if the directory doesn't already have the desired mode.
if [ -d "$REPO_ROOT/logs" ]; then
  _mode=$(stat -c %a "$REPO_ROOT/logs" 2>/dev/null || true)
  if [ -z "$_mode" ]; then
    chmod -R 0777 "$REPO_ROOT/logs" || true
  else
    if [ "$_mode" != "777" ]; then
      chmod -R 0777 "$REPO_ROOT/logs" || true
    fi
  fi
fi

# Ensure loki data directories exist and have reasonable perms. The Loki
# container runs as numeric UID 10001; if possible try to chown the folders to
# that UID so Loki can write to them. If sudo is available the script will
# attempt it (you may be prompted). If it fails we'll continue and leave a
# message for manual intervention.
# Ensure loki data directories exist and have reasonable perms. Only chmod
# each path if its current mode differs from the desired one.
for _p in "$REPO_ROOT/docker/loki-data" "$REPO_ROOT/docker/loki-wal"; do
  if [ -d "$_p" ]; then
    _mode=$(stat -c %a "$_p" 2>/dev/null || true)
    if [ -z "$_mode" ]; then
      chmod -R 0755 "$_p" || true
    else
      if [ "$_mode" != "755" ]; then
        chmod -R 0755 "$_p" || true
      fi
    fi
  fi
done
if [ "$(id -u)" -eq 0 ]; then
  chown -R 10001:10001 "$REPO_ROOT/docker/loki-data" "$REPO_ROOT/docker/loki-wal" || true
else
  if command -v sudo >/dev/null 2>&1; then
    echo "Attempting to chown loki folders to UID 10001 (may prompt for sudo password)"
    sudo chown -R 10001:10001 "$REPO_ROOT/docker/loki-data" "$REPO_ROOT/docker/loki-wal" || \
      echo "sudo chown failed or was cancelled; Loki may not start until these folders are owned by UID 10001"
  else
    echo "Note: sudo not available. Created loki folders but did not chown them." 
    echo "If Loki fails with permission errors, run:"
    echo "  sudo chown -R 10001:10001 $REPO_ROOT/docker/loki-data $REPO_ROOT/docker/loki-wal"
  fi
fi

# Stop and clean up any running containers/networks to prevent conflicts (especially if local db/cache are running)
echo "Stopping any existing compose services to prevent network conflicts..."
COMPOSE_ENV=$COMPOSE_ENV docker compose \
  -f docker/docker-compose.prod.yml \
  -f docker/docker-compose.local.yml \
  -f docker/docker-compose.test.yml \
  -f docker/docker-compose.dev.yml \
  down || true

if [ "$NO_BUILD" -eq 1 ]; then
  COMPOSE_ENV=$COMPOSE_ENV docker compose -f docker/docker-compose.prod.yml -f docker/docker-compose.dev.yml up
else
  COMPOSE_ENV=$COMPOSE_ENV docker compose -f docker/docker-compose.prod.yml -f docker/docker-compose.dev.yml up --build
fi
