set shell := ["bash", "-euo", "pipefail", "-c"]

# List available recipes
default:
    @just --list

# Bump the galaxy.yml version, commit, tag and push; CI publishes the tag to Galaxy
release version="":
    #!/usr/bin/env bash
    set -euo pipefail

    version="{{ version }}"
    current=$(grep '^version:' galaxy.yml | awk '{print $2}')

    if [[ -z "$version" ]]; then
        IFS=. read -r major minor patch <<< "$current"
        suggested="${major}.${minor}.$((patch + 1))"
        read -r -p "Version to release (current ${current}) [${suggested}]: " version
        version="${version:-$suggested}"
    fi
    tag="v${version}"

    if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
        echo "Error: version must be MAJOR.MINOR.PATCH, got '${version}'" >&2
        exit 1
    fi
    if [[ "$(printf '%s\n%s\n' "$current" "$version" | sort -V | tail -1)" != "$version" || "$current" == "$version" ]]; then
        echo "Error: version ${version} must be greater than the current version ${current}" >&2
        exit 1
    fi
    if [[ "$(git branch --show-current)" != "main" ]]; then
        echo "Error: releases must be made from main" >&2
        exit 1
    fi
    if [[ -n "$(git status --porcelain)" ]]; then
        echo "Error: working tree is not clean" >&2
        exit 1
    fi

    git fetch --quiet --tags origin main
    if [[ "$(git rev-parse HEAD)" != "$(git rev-parse origin/main)" ]]; then
        echo "Error: main is not in sync with origin/main" >&2
        exit 1
    fi
    if git rev-parse --quiet --verify "refs/tags/${tag}" >/dev/null; then
        echo "Error: tag ${tag} already exists" >&2
        exit 1
    fi

    read -r -p "Release ${tag} (was v${current})? Pushing the tag publishes it to Ansible Galaxy. [y/N] " answer
    if [[ ! "$answer" =~ ^[Yy]$ ]]; then
        echo "Aborted"
        exit 1
    fi

    printf "\033[0;32m>>> Release collection %s (was v%s)\033[0m\n" "$tag" "$current"
    sed "s/^version: .*/version: ${version}/" galaxy.yml > galaxy.yml.tmp && mv galaxy.yml.tmp galaxy.yml
    git add galaxy.yml
    git commit --quiet -m "chore: bump version to ${version}"
    git tag -a "$tag" -m "$tag"
    git push --atomic origin main "$tag"

    echo "Pushed ${tag}; follow the publish workflow with: gh run watch"
