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

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

if [[ ! -f .env ]]; then
  echo "Missing .env in $STACK_DIR"
  exit 1
fi

set -a
source .env
set +a

if [[ -z "${LAN_INTERFACE:-}" || -z "${LAN_SUBNET:-}" || -z "${LAN_GATEWAY:-}" || -z "${TECHNITIUM_BIND_IP:-}" || -z "${APPDATA_TECHNITIUM_ROOT:-}" ]]; then
  echo "LAN_INTERFACE, LAN_SUBNET, LAN_GATEWAY, TECHNITIUM_BIND_IP, and APPDATA_TECHNITIUM_ROOT must be set in .env"
  exit 1
fi

sudo mkdir -p "${APPDATA_TECHNITIUM_ROOT}/config" "${APPDATA_TECHNITIUM_ROOT}/logs"

echo "Validating compose config"
sudo docker compose --env-file .env config >/tmp/technitium-pilot-compose.rendered.yaml

echo "Rendered compose saved to /tmp/technitium-pilot-compose.rendered.yaml"

if [[ "${1:-}" == "--up" ]]; then
  echo "Starting Technitium pilot"
  sudo docker compose --env-file .env up -d
fi
