#!/bin/bash

if [[ -z "$ANSIBLE_GALAXY_TOKEN" ]] && [[ -z "$ANSIBLE_GALAXY_TOKEN_PATH" ]]; then
	echo >&2 "ERROR: Ansible Galaxy token not set in environment!"
	exit 1
fi

export __VERSION=$(yq -r ".version" galaxy.yml)
if [[ -z "$__VERSION" ]]; then
	echo >&2 "ERROR: Version not found from galaxy.yml!"
	exit 1
fi

export __GIT_TAG="$(git describe --exact-match --tags HEAD 2>/dev/null || echo '')"
if [[ -z "$__GIT_TAG" ]]; then
	echo >&2 "ERROR: Failed to get git tag!"
	exit 1
fi

if [[ "$__GIT_TAG" != "v$__VERSION" ]] ; then
	echo >&2 "ERROR: Version in galaxy.yml ($__VERSION) does not match git tag ($__GIT_TAG)!"
	exit 1
fi

__BUILD_ARTIFACT="samuliy-ansible-${__VERSION}.tar.gz"
if [[ ! -f "$__BUILD_ARTIFACT" ]]; then
	echo >&2 "ERROR: Build artifact ($__BUILD_ARTIFACT) not found!"
	exit 1
fi

echo "Deploying version: $__VERSION"
if [[ -n "$ANSIBLE_GALAXY_TOKEN" ]]; then
	ansible-galaxy collection publish "$__BUILD_ARTIFACT" --token "$ANSIBLE_GALAXY_TOKEN"
elif [[ -n "$ANSIBLE_GALAXY_TOKEN_PATH" ]]; then
	ansible-galaxy collection publish "$__BUILD_ARTIFACT" --token "$(cat "$ANSIBLE_GALAXY_TOKEN_PATH")"
else
	echo >&2 "ERROR: Ansible Galaxy token not found!"
	exit 1
fi
