#!/usr/bin/env bash
# build-multiarch.sh
# Builds and pushes a multi-arch Docker image (linux/amd64 + linux/arm64)
# directly from your local machine.
#
# Usage:
#   ./build-multiarch.sh yourDockerHubUsername
#   ./build-multiarch.sh yourDockerHubUsername v1.2.0
#
set -euo pipefail

DOCKERHUB_USER="${1:-}"
VERSION_TAG="${2:-latest}"

if [[ -z "$DOCKERHUB_USER" ]]; then
    echo "❌  Usage: $0 <dockerhub-username> [version-tag]"
    echo "    Example: $0 myname v1.0.0"
    exit 1
fi

IMAGE="${DOCKERHUB_USER}/ost2pst"
BUILDER="ost2pst-multiarch"

echo "▶  Image  : ${IMAGE}:${VERSION_TAG}"
echo "▶  Arches : linux/amd64, linux/arm64"
echo ""

# ── Ensure a buildx builder with multi-arch support exists ──────────────────
if ! docker buildx inspect "$BUILDER" &>/dev/null; then
    echo "Creating buildx builder '${BUILDER}'..."
    docker buildx create --name "$BUILDER" --driver docker-container --bootstrap
fi
docker buildx use "$BUILDER"

# ── Log in ───────────────────────────────────────────────────────────────────
echo "Logging in to Docker Hub as ${DOCKERHUB_USER}..."
docker login --username "$DOCKERHUB_USER"

# ── Build & push ─────────────────────────────────────────────────────────────
TAGS="-t ${IMAGE}:${VERSION_TAG}"
if [[ "$VERSION_TAG" != "latest" ]]; then
    TAGS="$TAGS -t ${IMAGE}:latest"
fi

echo ""
echo "Building and pushing (this may take a few minutes)..."
# shellcheck disable=SC2086
docker buildx build \
    --platform linux/amd64,linux/arm64 \
    $TAGS \
    --push \
    .

echo ""
echo "✅  Done!"
echo "    Image pushed:  ${IMAGE}:${VERSION_TAG}"
[[ "$VERSION_TAG" != "latest" ]] && echo "    Also tagged:   ${IMAGE}:latest"
echo ""
echo "    Pull anywhere:"
echo "      docker pull ${IMAGE}:${VERSION_TAG}"
echo "      docker run -d -p 3000:3000 -v \$(pwd)/converted:/app/converted ${IMAGE}:${VERSION_TAG}"
