#!/usr/bin/env bash
# Restore PostgreSQL / Redis exporters on 192.168.0.188 without host networking.
#
# Required on the host:
#   /home/ollama/monitoring/.env.exporters
#
# Required variables:
#   POSTGRES_EXPORTER_DATA_SOURCE_NAME=postgresql://...@192.168.0.188:5432/...?...sslmode=disable
#
# Optional variables:
#   REDIS_EXPORTER_ADDR=192.168.0.188:6380
#   REDIS_PASSWORD=

set -euo pipefail

ENV_FILE="${EXPORTER_ENV_FILE:-/home/ollama/monitoring/.env.exporters}"
QUERIES_FILE="${POSTGRES_EXPORTER_QUERIES_FILE:-/home/ollama/monitoring/postgres-exporter-queries.yaml}"
POSTGRES_IMAGE="${POSTGRES_EXPORTER_IMAGE:-prometheuscommunity/postgres-exporter:v0.15.0}"
REDIS_IMAGE="${REDIS_EXPORTER_IMAGE:-oliver006/redis_exporter:v1.58.0}"

if [ ! -f "$ENV_FILE" ]; then
  echo "EXPORTER_ENV_FILE_MISSING $ENV_FILE" >&2
  exit 2
fi

set -a
# shellcheck disable=SC1090
. "$ENV_FILE"
set +a

if [ -z "${POSTGRES_EXPORTER_DATA_SOURCE_NAME:-}" ]; then
  echo "POSTGRES_EXPORTER_DATA_SOURCE_NAME_MISSING" >&2
  exit 2
fi

if [ ! -f "$QUERIES_FILE" ]; then
  echo "POSTGRES_EXPORTER_QUERIES_FILE_MISSING $QUERIES_FILE" >&2
  exit 2
fi

REDIS_EXPORTER_ADDR="${REDIS_EXPORTER_ADDR:-192.168.0.188:6380}"
REDIS_PASSWORD="${REDIS_PASSWORD:-}"

docker rm -f postgres-exporter redis-exporter >/dev/null 2>&1 || true

docker run -d \
  --name postgres-exporter \
  --restart unless-stopped \
  -p 9187:9187 \
  -e DATA_SOURCE_NAME="$POSTGRES_EXPORTER_DATA_SOURCE_NAME" \
  -e PG_EXPORTER_EXTEND_QUERY_PATH=/etc/postgres_exporter/queries.yaml \
  -e PG_EXPORTER_LOG_LEVEL=info \
  -v "$QUERIES_FILE:/etc/postgres_exporter/queries.yaml:ro" \
  "$POSTGRES_IMAGE" >/dev/null

redis_args=(
  docker run -d
  --name redis-exporter
  --restart unless-stopped
  -p 9121:9121
  -e "REDIS_ADDR=$REDIS_EXPORTER_ADDR"
  -e "REDIS_EXPORTER_CHECK_KEYS=awoooi:*"
  -e REDIS_EXPORTER_INCL_SYSTEM_METRICS=true
)
if [ -n "$REDIS_PASSWORD" ]; then
  redis_args+=(-e "REDIS_PASSWORD=$REDIS_PASSWORD")
fi
redis_args+=("$REDIS_IMAGE")
"${redis_args[@]}" >/dev/null

pg_up="$(curl -fsS --max-time 5 http://127.0.0.1:9187/metrics | awk '/^pg_up / {print $2; exit}')"
redis_up="$(curl -fsS --max-time 5 http://127.0.0.1:9121/metrics | awk '/^redis_up / {print $2; exit}')"

echo "POSTGRES_EXPORTER_UP ${pg_up:-missing}"
echo "REDIS_EXPORTER_UP ${redis_up:-missing}"

test "${pg_up:-0}" = "1"
test "${redis_up:-0}" = "1"
