#!/bin/bash
# =============================================================================
# Build y Push de imagen SQL Server Low RAM a Docker Hub
# =============================================================================

set -e

IMAGE_NAME="andresgarcia0313/mssql-express-lowram"
VERSION="1.0"

cd "$(dirname "$0")"

echo "=== Building image: $IMAGE_NAME:$VERSION ==="
docker build -t "$IMAGE_NAME:$VERSION" -t "$IMAGE_NAME:latest" .

echo ""
echo "=== Testing image locally ==="
docker rm -f mssql-test 2>/dev/null || true

docker run -d \
    --name mssql-test \
    --memory="384m" \
    -e "MSSQL_SA_PASSWORD=TestPass123!" \
    -p 1434:1433 \
    "$IMAGE_NAME:latest"

echo "Esperando 30 segundos para que SQL Server inicie..."
sleep 30

if docker exec mssql-test /opt/mssql-tools/bin/sqlcmd \
    -S localhost -U sa -P 'TestPass123!' \
    -Q "SELECT 'TEST OK' AS Status" 2>/dev/null | grep -q "TEST OK"; then
    echo "✓ Test passed!"
    docker rm -f mssql-test
else
    echo "✗ Test failed!"
    docker logs mssql-test
    docker rm -f mssql-test
    exit 1
fi

echo ""
echo "=== Push to Docker Hub ==="
echo "Ejecuta: docker login"
echo "Luego:   docker push $IMAGE_NAME:$VERSION"
echo "         docker push $IMAGE_NAME:latest"
echo ""
echo "O ejecuta este script con 'push' como argumento:"
echo "  $0 push"

if [ "$1" == "push" ]; then
    docker push "$IMAGE_NAME:$VERSION"
    docker push "$IMAGE_NAME:latest"
    echo "✓ Push completado!"
fi
