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

GAL2_HOME="${GAL2_HOME:-/usr/local/gal2}"
GAL2_ENV="${GAL2_ENV:-/etc/gal2/daemon.env}"

export GAL2_CONFIG_FILE="$GAL2_ENV"

if [[ -f "$GAL2_ENV" ]]; then
  export GAL2_CONFIG_PRESENT=1
  set -a
  source "$GAL2_ENV"
  set +a
else
  export GAL2_CONFIG_PRESENT=0
fi

if [[ -n "${GAL2_API_KEY:-}" ]]; then
  export GAL2_API_KEY_PRESENT=1
else
  export GAL2_API_KEY_PRESENT=0
fi

export GAL2_API_URL="${GAL2_API_URL:-https://api-v2.gal-2.com/time}"
export GAL2_BIND_HOST="${GAL2_BIND_HOST:-127.0.0.1}"
export GAL2_BIND_PORT="${GAL2_BIND_PORT:-9095}"
export GAL2_CACHE_FILE="${GAL2_CACHE_FILE:-$GAL2_HOME/var/cache/gal2_cache.json}"
export GAL2_USAGE_FILE="${GAL2_USAGE_FILE:-$GAL2_HOME/var/usage/gal2_usage.json}"
export GAL2_ACTIVE_REFRESH_SEC="${GAL2_ACTIVE_REFRESH_SEC:-30}"
export GAL2_IDLE_REFRESH_SEC="${GAL2_IDLE_REFRESH_SEC:-120}"
export GAL2_HOLDOVER_RETRY_SEC="${GAL2_HOLDOVER_RETRY_SEC:-10}"
export GAL2_IDLE_AFTER_SEC="${GAL2_IDLE_AFTER_SEC:-60}"
export GAL2_REQUESTS_LIMIT="${GAL2_REQUESTS_LIMIT:-0}"
export GAL2_HTTP_TIMEOUT="${GAL2_HTTP_TIMEOUT:-10}"
export GAL2_MAX_SLEW_RATE="${GAL2_MAX_SLEW_RATE:-0.25}"
export PYTHONUNBUFFERED=1

cd "$GAL2_HOME"

if [[ -x "$GAL2_HOME/venv/bin/python3" ]]; then
  exec "$GAL2_HOME/venv/bin/python3" "$GAL2_HOME/bin/gal2d.py"
fi

exec /usr/bin/env python3 "$GAL2_HOME/bin/gal2d.py"
