#!/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,
#     builds the image with --build-arg VERSION=<new> and pushes it.
#
# 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"

# Current image reference (with tag), taken from the build command in DEPLOY.md
CURRENT_REF=$(grep -oP '(?<=-t )\S+:[0-9]+\.[0-9]+' "$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
sed -i "s/VERSION=${CURRENT_VERSION}\b/VERSION=${NEW_VERSION}/g; s/:${CURRENT_VERSION}\b/:${NEW_VERSION}/g" "$DEPLOY_FILE"

docker build --build-arg "VERSION=$NEW_VERSION" -t "$IMAGE:$NEW_VERSION" .
docker push "$IMAGE:$NEW_VERSION"

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'"
