#!/usr/bin/env bash
# Build and push a multi-arch Docker image tagged ghcr.io/<owner>/ezbeq:<tag>.
# Always rebuilds from source. Prompts for a tag if none supplied.
#
# Produces images for both linux/amd64 and linux/arm64 (override with PLATFORMS).
#
# Usage:
#   scripts/publish-image              # prompt for tag (default: dev)
#   scripts/publish-image dev         # build + push ghcr.io/<owner>/ezbeq:dev
#   scripts/publish-image dev v1.2.3  # multiple tags in one push
#   OWNER=3ll3d00d scripts/publish-image dev           # override GHCR owner
#   PLATFORMS=linux/amd64 scripts/publish-image dev    # single-arch (faster)
#
# Requires `docker login ghcr.io` (PAT with write:packages) and a buildx
# builder that supports the requested platforms. Docker Desktop works out
# of the box; elsewhere:
#   docker buildx create --name multi --use && docker buildx inspect --bootstrap
set -euo pipefail
# shellcheck source=_lib.sh
source "$(dirname "${BASH_SOURCE[0]}")/_lib.sh"
cd "$REPO_ROOT"

case "${1:-}" in
    -h|--help) ezbeq::print_help; exit 0 ;;
esac

PLATFORMS="${PLATFORMS:-linux/amd64,linux/arm64}"

ezbeq::resolve_owner
ezbeq::resolve_git_info

tags=("$@")
if [[ ${#tags[@]} -eq 0 ]]; then
    [[ -t 0 ]] || { echo "Error: no tag given and stdin is not a TTY." >&2; exit 2; }
    read -r -p "Image tag [dev]: " tag
    tags=("${tag:-dev}")
fi
for t in "${tags[@]}"; do ezbeq::validate_tag "$t"; done

if ! git -C "$REPO_ROOT" diff --quiet 2>/dev/null || ! git -C "$REPO_ROOT" diff --cached --quiet 2>/dev/null; then
    echo "Warning: uncommitted changes present; baked-in GIT_SHA ($GIT_SHA) won't reflect them." >&2
fi

tag_args=()
for t in "${tags[@]}"; do
    tag_args+=(-t "ghcr.io/${OWNER}/ezbeq:${t}")
done

REPO_URL="https://github.com/${OWNER}/ezbeq"

# Stamp ezbeq/VERSION with a PEP 440 local-version snapshot
# (<pyproject.version>+<branch>.<short-sha>) so the image banner makes clear
# this is an unreleased build. ezbeq/VERSION is gitignored. Tag releases go
# through CI, not this script.
BASE_VERSION=$(python3 -c "import tomllib; print(tomllib.load(open('$REPO_ROOT/pyproject.toml','rb'))['project']['version'])" 2>/dev/null || echo "0.0.0")
BRANCH_CLEAN=$(echo "${GIT_BRANCH:-unknown}" | tr -c '[:alnum:]' '.' | tr -s '.' | sed 's/^\.//; s/\.$//')
VERSION_STAMP="${BASE_VERSION}+${BRANCH_CLEAN}.${GIT_SHA:-unknown}"
echo "$VERSION_STAMP" > "$REPO_ROOT/ezbeq/VERSION"

echo "Owner     : $OWNER"
echo "Branch    : ${GIT_BRANCH:-unknown}"
echo "SHA       : ${GIT_SHA:-unknown}"
echo "Version   : $VERSION_STAMP"
echo "Platforms : $PLATFORMS"
echo "Tags      : ${tags[*]}"
echo "Repo URL  : $REPO_URL"
echo

docker buildx build \
    --platform "$PLATFORMS" \
    --target production \
    --build-arg "GIT_BRANCH=${GIT_BRANCH}" \
    --build-arg "GIT_SHA=${GIT_SHA}" \
    --build-arg "REPO_URL=${REPO_URL}" \
    -f "$REPO_ROOT/docker/Dockerfile" \
    "${tag_args[@]}" \
    --push \
    "$REPO_ROOT" || {
        echo "Error: buildx build/push failed. Did you run 'docker login ghcr.io' (PAT with write:packages)?" >&2
        echo "       For multi-arch builds, ensure your buildx builder supports $PLATFORMS." >&2
        exit 1
    }

echo
echo "Published ${#tags[@]} tag(s) to ghcr.io/${OWNER}/ezbeq for platforms: $PLATFORMS"
