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

if [[ "${EUID}" -ne 0 ]]; then
  echo "Please run as root: sudo ./scripts/activate.sh"
  exit 1
fi

printf "Enter GAL-2 API key: "
stty -echo
IFS= read -r GAL2_API_KEY
stty echo
printf "\n"

mkdir -p /etc/gal2

cat > /etc/gal2/daemon.env <<ENV
GAL2_API_KEY=$GAL2_API_KEY
GAL2_API_URL=https://api-v2.gal-2.com/time
GAL2_BIND_HOST=127.0.0.1
GAL2_BIND_PORT=9095
GAL2_CACHE_FILE=/usr/local/gal2/var/cache/gal2_cache.json
GAL2_USAGE_FILE=/usr/local/gal2/var/usage/gal2_usage.json
GAL2_ACTIVE_REFRESH_SEC=30
GAL2_IDLE_REFRESH_SEC=120
GAL2_HOLDOVER_RETRY_SEC=10
GAL2_IDLE_AFTER_SEC=60
GAL2_REQUESTS_LIMIT=0
GAL2_HTTP_TIMEOUT=10
GAL2_MAX_SLEW_RATE=0.25
GAL2_CONTRACT_LIVE_VALID_SEC=45
GAL2_CONTRACT_HOLDOVER_SOFT_SEC=300
GAL2_CONTRACT_HOLDOVER_HARD_SEC=900
GAL2_CONTRACT_MAX_API_LATENCY_MS=5000
GAL2_CONTRACT_REJOIN_GUARD_SEC=10
GAL2_DAEMON_VERSION=1.0.0-rc3
GAL2_CONTRACT_VERSION=1.0.0-contract-rc3
ENV

chmod 600 /etc/gal2/daemon.env
unset GAL2_API_KEY

if command -v systemctl >/dev/null 2>&1; then
  systemctl restart gal2d.service
fi

echo "GAL-2 API key installed at /etc/gal2/daemon.env"
