#!/usr/bin/env bash
# bin/setup-env — create /etc/dispatch/env from the repo .env with system paths.
# Run this once before bin/install (or after, to refresh the config).
#
# Usage: sudo bin/setup-env

set -euo pipefail

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

if [[ "$(id -u)" -ne 0 ]]; then
	echo "setup-env: must run as root (use sudo)" >&2
	exit 1
fi

mkdir -p /etc/dispatch /var/lib/dispatch /var/log/dispatch

# Read the API keys from the repo .env (gitignored, local only)
ENV_FILE="$ROOT/.env"
if [[ ! -f "$ENV_FILE" ]]; then
	echo "setup-env: $ENV_FILE not found — create it first (see .env.example)" >&2
	exit 1
fi

# Extract values from .env
source "$ENV_FILE"

# Resolve the real user's home dir (the service runs as this user — see bin/install)
REAL_USER="${SUDO_USER:-$USER}"
REAL_GROUP=$(id -gn "$REAL_USER" 2>/dev/null || echo "$REAL_USER")
REAL_HOME=$(getent passwd "$REAL_USER" | cut -d: -f6)
if [[ -z "$REAL_HOME" ]]; then
	echo "setup-env: could not resolve home for user '$REAL_USER'" >&2
	exit 1
fi

# Ensure data dirs are owned by the real user (the service runs as them)
mkdir -p /var/lib/dispatch /var/log/dispatch
chown -R "$REAL_USER:$REAL_GROUP" /var/lib/dispatch /var/log/dispatch

# Write the system env file
tee /etc/dispatch/env > /dev/null << EOF
# /etc/dispatch/env — Dispatch server configuration (systemd EnvironmentFile)
# Generated by bin/setup-env from $ENV_FILE
# Edit manually, then: systemctl restart dispatch

# ─── User environment (service runs as $REAL_USER, homedir is correct) ───────
HOME=$REAL_HOME

# ─── Ports ───────────────────────────────────────────────────────────────────
BACKEND_PORT=24991
SURFACE_WS_PORT=24990

# ─── Frontend ────────────────────────────────────────────────────────────────
DISPATCH_WEB_DIR=/usr/share/dispatch/web

# ─── Provider (OpenCode Go / OpenAI-compatible) ──────────────────────────────
DISPATCH_API_KEY=${DISPATCH_API_KEY}
DISPATCH_BASE_URL=${DISPATCH_BASE_URL:-https://opencode.ai/zen/go/v1}
DISPATCH_MODEL=${DISPATCH_MODEL:-deepseek-v4-flash}

# ─── Umans provider ──────────────────────────────────────────────────────────
${UMANS_API_KEY:+UMANS_API_KEY=${UMANS_API_KEY}}

# ─── Data paths ──────────────────────────────────────────────────────────────
DISPATCH_DB=/var/lib/dispatch/dispatch.db
DISPATCH_TRACE_DB=/var/lib/dispatch/traces.db
DISPATCH_JOURNAL=/var/log/dispatch/app.ndjson
EOF

chmod 600 /etc/dispatch/env

echo "[setup-env] wrote /etc/dispatch/env"
echo "  HOME=$REAL_HOME (skills: $REAL_HOME/.skills/)"
echo "  DISPATCH_API_KEY=${DISPATCH_API_KEY:0:8}..."
${UMANS_API_KEY:+echo "  UMANS_API_KEY=${UMANS_API_KEY:0:8}..."}
echo "  Ports: HTTP=24991 WS=24990"
echo "  Data:  /var/lib/dispatch/ + /var/log/dispatch/"
