#!/bin/sh
set -e

NEXUS_URL="${NEXUS_URL:-http://nexus:8081}"
ADMIN_PASSWORD="${ADMIN_PASSWORD:-admin123}"
WEBHOOK_URL="${WEBHOOK_URL:-http://guarddog-nexus:8080/webhooks/nexus}"

apk add --no-cache curl >/dev/null 2>&1 || true

echo "Waiting for Nexus to start..."
MAX_WAIT=300
ELAPSED=0
while [ $ELAPSED -lt $MAX_WAIT ]; do
    if curl -sf -o /dev/null "${NEXUS_URL}/service/rest/v1/status" 2>/dev/null; then
        echo "Nexus is up."
        break
    fi
    sleep 5
    ELAPSED=$((ELAPSED + 5))
done

if [ $ELAPSED -ge $MAX_WAIT ]; then
    echo "Timed out waiting for Nexus" >&2
    exit 1
fi

AUTH_PASS="$ADMIN_PASSWORD"
if [ -f /nexus-data/admin.password ]; then
    AUTH_PASS=$(cat /nexus-data/admin.password)
    echo "Using initial admin password from volume"
fi

# Common proxy config
_proxy_config() {
    cat <<EOF
{
    "name": "$1",
    "online": true,
    "storage": {
        "blobStoreName": "default",
        "strictContentTypeValidation": true
    },
    "proxy": {
        "remoteUrl": "$2",
        "contentMaxAge": 1440,
        "metadataMaxAge": 1440
    },
    "negativeCache": {
        "enabled": true,
        "timeToLive": 1440
    },
    "httpClient": {
        "blocked": false,
        "autoBlock": true,
        "connection": {
            "timeout": 60,
            "retries": 3
        }
    }
}
EOF
}

_create_proxy() {
    local name="$1" remote="$2" format="$3"
    echo "Creating $name ($format proxy → $remote)..."
    curl -sf -u "admin:${AUTH_PASS}" \
        -H "Content-Type: application/json" \
        -X POST \
        -d "$(_proxy_config "$name" "$remote")" \
        "${NEXUS_URL}/service/rest/v1/repositories/${format}/proxy" 2>/dev/null && \
        echo "  OK" || echo "  already exists or failed, continuing..."
}

_create_proxy "pypi-proxy" "https://pypi.org" "pypi"
_create_proxy "go-proxy" "https://proxy.golang.org" "go"
_create_proxy "npm-proxy" "https://registry.npmjs.org" "npm"

echo ""
echo "NOTE: Webhook setup is not available in Nexus OSS/Community edition."
echo "In Nexus Pro, configure:"
echo "  Capability: Webhook: Repository"
echo "  URL: ${WEBHOOK_URL}"
echo "  Event types: repository.component, repository.asset"
echo "  Repository filter: pypi-proxy, go-proxy, npm-proxy"
echo ""

if [ -f /nexus-data/admin.password ]; then
    echo "Changing default admin password..."
    curl -sf -u "admin:${AUTH_PASS}" \
        -H "Content-Type: text/plain" \
        -X PUT \
        -d "${ADMIN_PASSWORD}" \
        "${NEXUS_URL}/service/rest/v1/security/users/admin/change-password" 2>/dev/null || true
fi

echo "Nexus setup complete."
