#!/usr/bin/env bash
# Expand {{VAR}} placeholders in .env, then start Docker Compose.
set -euo pipefail

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

if [[ ! -f .env ]]; then
  echo "Missing .env — run: cp .env.example .env" >&2
  exit 1
fi

if command -v go >/dev/null 2>&1; then
  go run ./cmd/envexpand -in .env -out .env.resolved
else
  if [[ ! -x ./ultid-envexpand ]] && [[ ! -f ./bin/envexpand ]]; then
    echo "Go not found and envexpand binary missing. Install Go or build: go build -o bin/envexpand ./cmd/envexpand" >&2
    exit 1
  fi
  ./bin/envexpand -in .env -out .env.resolved 2>/dev/null || ./ultid-envexpand -in .env -out .env.resolved
fi

to_bool() {
  local value="${1:-}"
  value="$(printf '%s' "$value" | tr '[:upper:]' '[:lower:]')"
  case "$value" in
    1|true|yes|on) echo "true" ;;
    *) echo "false" ;;
  esac
}

# shellcheck disable=SC1091
set -a
source .env.resolved
set +a

compose_files=(
  "-f" "deploy/docker-compose.yml"
)

if [[ "$(to_bool "${NEXTCLOUD_ENABLED:-false}")" == "true" ]]; then
  compose_files+=("-f" "deploy/nextcloud/docker-compose.nextcloud.yml")
fi

if [[ "$(to_bool "${JITSI_ENABLED:-false}")" == "true" ]]; then
  compose_files+=("-f" "deploy/jitsi/docker-compose.jitsi.yml")
fi

if [[ "$(to_bool "${IMMICH_ENABLED:-false}")" == "true" ]]; then
  compose_files+=("-f" "deploy/immich/docker-compose.immich.yml")
fi

if [[ "$(to_bool "${ONLYOFFICE_ENABLED:-false}")" == "true" ]]; then
  compose_files+=("-f" "deploy/onlyoffice/docker-compose.onlyoffice.yml")
fi

exec docker compose --env-file .env.resolved "${compose_files[@]}" "$@"
