#!/bin/bash
set -euo pipefail

# Easy Gate is entirely config-file driven. The config lives in /app/data so
# it survives restarts and updates; seed a Cloudron-friendly default on first
# run. "behind_proxy" is true because Cloudron fronts the app with its nginx:
# X-Forwarded-For carries the real client IP, which the group subnet matching
# relies on.

export EASY_GATE_CONFIG_PATH="/app/data/easy-gate.json"

if [[ ! -f "${EASY_GATE_CONFIG_PATH}" ]]; then
  cat > "${EASY_GATE_CONFIG_PATH}" <<'EOF'
{
  "addr": "0.0.0.0:8080",
  "use_tls": false,
  "cert_file": "",
  "key_file": "",
  "behind_proxy": true,
  "title": "Easy Gate",
  "theme": {
    "background": "#FFFFFF",
    "foreground": "#000000"
  },
  "groups": [
    {
      "name": "lan",
      "subnet": "192.168.0.0/16"
    }
  ],
  "services": [
    {
      "name": "Cloudron",
      "category": "Platform",
      "url": "https://my.example.com",
      "groups": []
    }
  ],
  "notes": [
    {
      "name": "How to configure",
      "text": "Edit /app/data/easy-gate.json with the Cloudron file manager. Easy Gate re-parses the config every second: changes apply immediately, no restart needed.",
      "groups": []
    }
  ]
}
EOF
  echo "Seeded default config at ${EASY_GATE_CONFIG_PATH}"
fi

exec /usr/local/bin/easy-gate
