#!/bin/bash
# Build and push base image locally
# Usage: ./build-base-local.sh

set -e

echo "════════════════════════════════════════"
echo "  🔨 Building Base Image Locally"
echo "════════════════════════════════════════"
echo ""

# Configuration
REGISTRY="hub.peikarband.ir"
REPO="peikarband/base"
TAG="latest"
PYTHON_VERSION="3.11"
NODE_VERSION="20"

# Full image name
IMAGE="${REGISTRY}/${REPO}:${TAG}"

echo "📦 Image: ${IMAGE}"
echo "🐍 Python: ${PYTHON_VERSION}"
echo "📦 Node.js: ${NODE_VERSION}"
echo ""

# Check if docker buildx is available
if ! docker buildx version &> /dev/null; then
    echo "❌ docker buildx not found!"
    echo "Please install Docker Buildx"
    exit 1
fi

# Login to registry
echo "🔐 Logging in to registry..."
echo ""
read -p "Harbor Username: " HARBOR_USERNAME
read -sp "Harbor Password: " HARBOR_PASSWORD
echo ""
echo ""

echo "$HARBOR_PASSWORD" | docker login "$REGISTRY" -u "$HARBOR_USERNAME" --password-stdin

# Create/use buildx builder
echo ""
echo "🏗️  Setting up builder..."
docker buildx create --use --name peikarband-builder 2>/dev/null || docker buildx use peikarband-builder

# Build and push
echo ""
echo "🔨 Building base image..."
echo "(This will take ~8-10 minutes on first build)"
echo ""

docker buildx build \
  -f docker/Dockerfile.base \
  -t "${IMAGE}" \
  -t "${REGISTRY}/${REPO}:python${PYTHON_VERSION}-node${NODE_VERSION}" \
  --build-arg PYTHON_VERSION="${PYTHON_VERSION}" \
  --build-arg NODE_VERSION="${NODE_VERSION}" \
  --platform linux/amd64 \
  --push \
  --progress=plain \
  .

echo ""
echo "════════════════════════════════════════"
echo "  ✅ Base Image Built Successfully!"
echo "════════════════════════════════════════"
echo ""
echo "📦 Image: ${IMAGE}"
echo ""
echo "Tags pushed:"
echo "  • latest"
echo "  • python${PYTHON_VERSION}-node${NODE_VERSION}"
echo ""
echo "Now you can build your app with:"
echo "  make docker-build"
echo ""
echo "Or in CI, it will automatically use this base image."
echo ""

