#!/bin/bash

# Verify inputs
if [ -z "$1" ] || [ -z "$2" ]; then
  echo "❌ Usage: ./build-and-push.sh <dockerhub-username> <repository-name> [tag]"
  exit 1
fi

USERNAME=$1
REPOSITORY=$2
TAG=${3:-latest} # Default tag is 'latest'
IMAGE_NAME="$USERNAME/$REPOSITORY:$TAG"

echo "🔹 Checking Docker login..."

# More reliable way to check Docker login status
if ! docker system info > /dev/null 2>&1; then
  echo "❌ Cannot connect to Docker daemon. Is Docker running?"
  exit 1
fi

# Check if we can access Docker Hub
if ! docker pull hello-world > /dev/null 2>&1; then
  echo "❌ Not authenticated with Docker Hub or no network connection"
  echo "🔹 Please log in by running: docker login"
  echo "🔹 Then re-run this script."
  exit 1
fi

echo "✅ Docker Hub authentication verified"

echo "🔹 Setting up buildx..."
docker buildx create --name multiarch --use || true
docker buildx inspect --bootstrap

echo "🔹 Building multi-platform Docker image..."
docker buildx build \
  --platform linux/amd64,linux/arm64 \
  -t "$IMAGE_NAME" \
  --push . || { echo "❌ Build failed"; exit 1; }

echo "✅ Images successfully pushed to Docker Hub for both platforms: $IMAGE_NAME"