#!/usr/bin/env bash
# Publish a new MeTube docker image.
#
# Implements the versioning rule (see DEPLOY.md / AGENTS.md):
#   - The version recorded in DEPLOY.md (checked into git) is the current
#     online version.
#   - Publishing bumps the minor number of that version, updates DEPLOY.md,
#     cross-builds the image for the target platform (buildx) with
#     --build-arg VERSION=<new> and pushes it to the registry.
#
# Usage:
#   ./publish.sh            # bump minor of the current version (e.g. 1.10 -> 1.11)
#   ./publish.sh 2.0        # publish an explicit version instead

set -euo pipefail
cd "$(dirname "$0")"

DEPLOY_FILE="DEPLOY.md"

# Deployment target platform (Ubuntu 22.04 x86_64). The local dev machine is
# Apple Silicon (arm64), so builds go through `docker buildx`.
PLATFORM="linux/amd64"

# Current image reference (with tag), taken from the build command in DEPLOY.md.
# Written with POSIX sed so it works with macOS's BSD userland (no GNU grep -P).
CURRENT_REF=$(sed -n 's/.*-t \([^ ]*:[0-9][0-9]*\.[0-9][0-9]*\).*/\1/p' "$DEPLOY_FILE" | head -1)
if [[ -z "$CURRENT_REF" ]]; then
  echo "Error: could not find an image reference like '-t <registry>/<image>:<major>.<minor>' in $DEPLOY_FILE" >&2
  exit 1
fi

IMAGE="${CURRENT_REF%:*}"            # e.g. 192.168.2.212:3000/tigeren/metube
CURRENT_VERSION="${CURRENT_REF##*:}" # e.g. 1.10

if [[ $# -ge 1 ]]; then
  NEW_VERSION="$1"
else
  MAJOR="${CURRENT_VERSION%%.*}"
  MINOR="${CURRENT_VERSION##*.}"
  NEW_VERSION="$MAJOR.$((MINOR + 1))"
fi

if ! [[ "$NEW_VERSION" =~ ^[0-9]+\.[0-9]+$ ]]; then
  echo "Error: version must be in <major>.<minor> form, got '$NEW_VERSION'" >&2
  exit 1
fi

if [[ "$NEW_VERSION" == "$CURRENT_VERSION" ]]; then
  echo "Error: new version $NEW_VERSION equals current version" >&2
  exit 1
fi

echo "Publishing $IMAGE:$NEW_VERSION (current: $CURRENT_VERSION)"

# Record the new version as the current online version. BSD sed has no `\b`,
# so require a non-digit (or end of line) after the version to avoid matching
# e.g. 1.1 inside 1.10.
sed -i '' \
  -e "s/VERSION=${CURRENT_VERSION}\([^0-9.]\)/VERSION=${NEW_VERSION}\1/g" \
  -e "s/VERSION=${CURRENT_VERSION}\$/VERSION=${NEW_VERSION}/g" \
  -e "s/:${CURRENT_VERSION}\([^0-9.]\)/:${NEW_VERSION}\1/g" \
  -e "s/:${CURRENT_VERSION}\$/:${NEW_VERSION}/g" \
  "$DEPLOY_FILE"

# Cross-build from the local machine (e.g. Apple Silicon) for the deployment
# target platform and push directly to the registry in one buildx invocation.
docker buildx build \
  --platform "$PLATFORM" \
  --build-arg "VERSION=$NEW_VERSION" \
  -t "$IMAGE:$NEW_VERSION" \
  --push \
  .

echo
echo "Published $IMAGE:$NEW_VERSION"
echo "DEPLOY.md updated to the new current online version."
echo "Suggested next step:"
echo "  git add -A && git commit -m 'Publish v$NEW_VERSION'"
