#!/usr/bin/env bash
# Sync explorer-config-api DATABASE_URL to the live blockscout-postgres container IP.
# Run inside VMID 5000 (or via pct exec). Safe to run from cron every 5 minutes.
set -euo pipefail

SERVICE="${EXPLORER_CONFIG_API_SERVICE:-explorer-config-api}"
DROPIN_DIR="/etc/systemd/system/${SERVICE}.service.d"
DROPIN_FILE="${DROPIN_DIR}/database.conf"
CONTAINER="${BLOCKSCOUT_POSTGRES_CONTAINER:-blockscout-postgres}"
DB_USER="${BLOCKSCOUT_DB_USER:-blockscout}"
DB_PASSWORD="${BLOCKSCOUT_DB_PASSWORD:-blockscout}"
DB_NAME="${BLOCKSCOUT_DB_NAME:-blockscout}"

if ! command -v docker >/dev/null 2>&1; then
  echo "docker not available" >&2
  exit 1
fi

if ! docker ps --format '{{.Names}}' | grep -qx "$CONTAINER"; then
  echo "postgres container not running: $CONTAINER" >&2
  exit 1
fi

DB_IP="$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "$CONTAINER" 2>/dev/null || true)"
if [ -z "$DB_IP" ]; then
  echo "could not resolve IP for $CONTAINER" >&2
  exit 1
fi

DESIRED_URL="postgresql://${DB_USER}:${DB_PASSWORD}@${DB_IP}:5432/${DB_NAME}?sslmode=disable"
CURRENT_URL=""
if [ -f "$DROPIN_FILE" ]; then
  CURRENT_URL="$(grep -E '^Environment=DATABASE_URL=' "$DROPIN_FILE" | head -1 | sed 's/^Environment=DATABASE_URL=//' || true)"
fi

mkdir -p "$DROPIN_DIR"
if [ "$CURRENT_URL" = "$DESIRED_URL" ]; then
  echo "DATABASE_URL already current ($DB_IP)"
  exit 0
fi

cat > "$DROPIN_FILE" <<EOF
[Service]
Environment=DATABASE_URL=${DESIRED_URL}
EOF
chmod 600 "$DROPIN_FILE"

systemctl daemon-reload
systemctl restart "$SERVICE"
sleep 2

if ! systemctl is-active --quiet "$SERVICE"; then
  echo "restart failed for $SERVICE" >&2
  systemctl status "$SERVICE" --no-pager -l || true
  exit 1
fi

echo "updated DATABASE_URL -> ${DB_IP} and restarted ${SERVICE}"
