#!/bin/bash
# =============================================================================
# Actualizar README en Docker Hub Overview
# =============================================================================
# Uso: ./update-dockerhub-readme.sh <username> <password>
# =============================================================================

set -e

DOCKER_USER="${1:-andresgarcia0313}"
DOCKER_PASS="$2"
REPO_NAME="mssql-express-lowram"
README_FILE="$(dirname "$0")/README.md"

if [ -z "$DOCKER_PASS" ]; then
    echo "Uso: $0 <username> <password>"
    echo "  o: $0 <username> (te pedirá el password)"
    read -s -p "Docker Hub Password: " DOCKER_PASS
    echo ""
fi

echo "=== Obteniendo token de Docker Hub ==="
TOKEN=$(curl -s -X POST "https://hub.docker.com/v2/users/login/" \
    -H "Content-Type: application/json" \
    -d "{\"username\":\"$DOCKER_USER\",\"password\":\"$DOCKER_PASS\"}" | jq -r '.token')

if [ -z "$TOKEN" ] || [ "$TOKEN" == "null" ]; then
    echo "Error: No se pudo obtener token. Verifica credenciales."
    exit 1
fi

echo "=== Token obtenido correctamente ==="

echo "=== Actualizando README en Docker Hub ==="
README_CONTENT=$(cat "$README_FILE" | jq -Rs .)

RESPONSE=$(curl -s -X PATCH "https://hub.docker.com/v2/repositories/$DOCKER_USER/$REPO_NAME/" \
    -H "Authorization: Bearer $TOKEN" \
    -H "Content-Type: application/json" \
    -d "{\"full_description\":$README_CONTENT}")

if echo "$RESPONSE" | jq -e '.full_description' > /dev/null 2>&1; then
    echo "✅ README actualizado exitosamente en Docker Hub"
    echo "   https://hub.docker.com/r/$DOCKER_USER/$REPO_NAME"
else
    echo "❌ Error al actualizar:"
    echo "$RESPONSE" | jq .
    exit 1
fi
