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

# Deploy UNPoller on tsys-librenms
# Part of OAM platform [#337]
# UniFi controller polling for metrics export

echo "=== Setting up UNPoller ==="

mkdir -p /opt/oam/unpoller

# Write config
cat > /opt/oam/unpoller/up.conf <<'CONFEOF'
[poller]
debug = false
quiet = false
plugins = []

[unifi.defaults]
url = "https://pfv-bms.knel.net:8443"
user = "CHANGE_ME"
pass = "CHANGE_ME"
sites = ["all"]
ssl_verify = false

[unifi.defaults.save_dpi]
enabled = true

[influxdb]
enable = false
url = "http://tsys-librenms.knel.net:8086"
db = "unifi"

[datadog]
enable = false

[prometheus]
enable = true
http_listen = ":9130"
report_errors = true

[loki]
enable = false
CONFEOF

# Docker compose
cat > /opt/oam/unpoller/docker-compose.yml <<'DCEOF'
services:
  unpoller:
    image: ghcr.io/unpoller/unpoller:latest
    container_name: oam-unpoller
    environment:
      - UP_UNIFI_DEFAULT_URL=https://pfv-bms.knel.net:8443
      - UP_UNIFI_DEFAULT_USER=CHANGE_ME
      - UP_UNIFI_DEFAULT_PASS=CHANGE_ME
      - UP_UNIFI_DEFAULT_VERIFY_SSL=false
      - UP_PROMETHEUS_ENABLE=true
      - UP_PROMETHEUS_HTTP_LISTEN=:9130
      - TZ=America/Chicago
    ports:
      - "8084:9130"
    volumes:
      - /opt/oam/unpoller/up.conf:/config/unifi-poller.conf:ro
    restart: unless-stopped
DCEOF

echo "=== Pulling UNPoller image ==="
cd /opt/oam/unpoller && timeout 120 docker compose pull 2>&1

echo "=== Starting UNPoller ==="
cd /opt/oam/unpoller && docker compose up -d 2>&1

echo "=== Status ==="
docker ps --filter name=oam-unpoller --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"

echo ""
echo "=== IMPORTANT ==="
echo "UNPoller deployed with placeholder UniFi credentials (CHANGE_ME)."
echo "Update UP_UNIFI_DEFAULT_USER and UP_UNINI_DEFAULT_PASS env vars"
echo "in /opt/oam/unpoller/docker-compose.yml with real UniFi controller"
echo "credentials, then restart: cd /opt/oam/unpoller && docker compose up -d"
echo ""
echo "=== UNPoller Prometheus metrics: http://tsys-librenms.knel.net:8084 ==="
