#!/usr/bin/env bash
# ─────────────────────────────────────────────────────────────────────────────
# Switch the Nexus Docker proxy upstream to Liara mirror (or back to Docker Hub)
#
# Usage (with Liara):
#   DOCKER_MIRROR_URL=https://docker-mirror.liara.ir \
#   DOCKER_MIRROR_USER=your-liara-email \
#   DOCKER_MIRROR_PASS=your-liara-token \
#   NEXUS_ADMIN_PASS=Mirror@2024! \
#   ./mirrors/nexus/update-docker-upstream.sh
#
# Usage (back to Docker Hub direct):
#   NEXUS_ADMIN_PASS=Mirror@2024! ./mirrors/nexus/update-docker-upstream.sh
# ─────────────────────────────────────────────────────────────────────────────
set -euo pipefail

NEXUS_URL="http://localhost:8081"
ADMIN_PASS="${NEXUS_ADMIN_PASS:-Mirror@2024!}"
AUTH="-u admin:$ADMIN_PASS"

DOCKER_UPSTREAM="${DOCKER_MIRROR_URL:-https://registry-1.docker.io}"
DOCKER_USER="${DOCKER_MIRROR_USER:-}"
DOCKER_PASS="${DOCKER_MIRROR_PASS:-}"

if [ -n "$DOCKER_USER" ] && [ -n "$DOCKER_PASS" ]; then
  AUTH_BLOCK='"authentication":{"type":"username","username":"'"$DOCKER_USER"'","password":"'"$DOCKER_PASS"'"},'
  INDEX_TYPE="REGISTRY"
  echo "🐳  Switching Docker proxy → $DOCKER_UPSTREAM (with auth)"
else
  AUTH_BLOCK=""
  INDEX_TYPE="HUB"
  echo "🐳  Switching Docker proxy → $DOCKER_UPSTREAM (no auth)"
fi

HTTP=$(curl -s -o /dev/null -w "%{http_code}" $AUTH \
  -X PUT "$NEXUS_URL/service/rest/v1/repositories/docker/proxy/docker-hub-proxy" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "docker-hub-proxy",
    "online": true,
    "storage": {
      "blobStoreName": "default",
      "strictContentTypeValidation": true
    },
    "proxy": {
      "remoteUrl": "'"$DOCKER_UPSTREAM"'",
      "contentMaxAge": 1440,
      "metadataMaxAge": 1440
    },
    "negativeCache": { "enabled": true, "timeToLive": 1440 },
    "httpClient": {
      "blocked": false,
      "autoBlock": true,
      '"$AUTH_BLOCK"'
      "connection": { "useTrustStore": false }
    },
    "docker": {
      "v1Enabled": false,
      "forceBasicAuth": false,
      "httpPort": 8083
    },
    "dockerProxy": {
      "indexType": "'"$INDEX_TYPE"'",
      "cacheForeignLayers": false
    }
  }')

if [ "$HTTP" = "204" ]; then
  echo "✅  docker-hub-proxy updated → $DOCKER_UPSTREAM"
else
  echo "❌  Update failed — HTTP $HTTP"
  exit 1
fi
