#!/usr/bin/env bash
set -Eeuo pipefail

if [[ $# -ne 2 ]]; then
	echo "usage: $0 <RELEASE_BRANCH> <TAG>" >&2
	exit 1
fi

release_branch="$1"
tag="$2"

if [[ "$tag" == *"-rc."* ]]; then
	echo "error: RC tags cannot be used as sync targets" >&2
	exit 1
fi

if [[ "$tag" != v* ]]; then
	echo "error: Tag must start with 'v' (e.g. v29.6.0)" >&2
	exit 1
fi

if ! git rev-parse --verify --quiet "refs/tags/$tag" > /dev/null; then
	echo "error: Tag $tag does not exist" >&2
	exit 1
fi

# Return early the requested tag is already merged into release branch.
if git merge-base --is-ancestor "$tag" "$release_branch"; then
	exit 0
fi

if git rev-parse --verify --quiet upstream/master > /dev/null 2>&1; then
	master="upstream/master"
else
	master="origin/master"
fi

if ! git merge-base --is-ancestor "$tag" "$master"; then
       echo "error: Tag $tag is not in $master" >&2
       exit 1
fi

# Get all docker release tags merged into master but not into release branch
git tag --merged "$master" --no-merged "$release_branch" \
	| grep '^v' \
	| grep -v -- "-rc." \
	| sort -V \
	| awk -v tag="$tag" '{print} $0==tag{exit}'
