#!/usr/bin/env bash
# Genererer /tmp/maskinrommet.env med Docker container-IP-er.
# Kjøres av systemd ExecStartPre.

set -euo pipefail

ENV_FILE="/srv/synops/.env"
read_env() { grep "^$1=" "$ENV_FILE" | head -1 | cut -d= -f2; }
container_ip() { docker inspect "$1" --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}'; }

PG_IP=$(container_ip sidelinja-postgres-1)
WHISPER_IP=$(container_ip sidelinja-faster-whisper-1 2>/dev/null || echo "")
AI_GW_IP=$(container_ip sidelinja-ai-gateway-1 2>/dev/null || echo "")
LIVEKIT_IP=$(container_ip sidelinja-livekit-1 2>/dev/null || echo "")

cat > /tmp/maskinrommet.env <<EOF
DATABASE_URL=postgres://$(read_env POSTGRES_USER):$(read_env POSTGRES_PASSWORD)@${PG_IP}:5432/synops
AUTHENTIK_ISSUER=$(read_env AUTHENTIK_ISSUER)
AUTHENTIK_CLIENT_ID=$(read_env AUTHENTIK_CLIENT_ID)
BIND_ADDR=0.0.0.0:3100
CAS_ROOT=/srv/synops/media/cas
WHISPER_URL=http://${WHISPER_IP:-localhost}:8000
AI_GATEWAY_URL=http://${AI_GW_IP:-localhost}:4000
LITELLM_MASTER_KEY=$(read_env LITELLM_MASTER_KEY)
LIVEKIT_URL=http://${LIVEKIT_IP:-localhost}:7880
LIVEKIT_API_KEY=$(read_env LIVEKIT_API_KEY)
LIVEKIT_API_SECRET=$(read_env LIVEKIT_API_SECRET)
LIVEKIT_WS_URL=$(read_env LIVEKIT_WS_URL)
ELEVENLABS_API_KEY=$(read_env ELEVENLABS_API_KEY)
ELEVENLABS_DEFAULT_VOICE=$(read_env ELEVENLABS_DEFAULT_VOICE)
ELEVENLABS_MODEL=$(read_env ELEVENLABS_MODEL)
PROJECT_DIR=/home/vegard/synops
SYNOPS_CLIP_SCRIPTS=/home/vegard/synops/tools/synops-clip/scripts
SYNOPS_MASTER_KEY=$(read_env SYNOPS_MASTER_KEY)
RUST_LOG=maskinrommet=debug,tower_http=debug
EOF
