#!/bin/bash
set -e

if [ -z "$NAMESPACE" ]; then
    echo "Error: NAMESPACE is not set."
    exit 1
fi

if [ -z "$COLLECTION" ]; then
    echo "Error: COLLECTION name is not set."
    exit 1
fi

if [ -z "$VERSION" ]; then
    echo "Error: VERSION is not set."
    exit 1
fi

ARTIFACT="${NAMESPACE}-${COLLECTION}-${VERSION}.tar.gz"
SECRET_FILE="/run/secrets/galaxy_token"

[ -f $ARTIFACT ] || {
    echo "Error: Artifact \"${ARTIFACT}\" not found."
    exit 1
}

[ -f "$SECRET_FILE" ] || {
    echo "Error: Secret not found at ${SECRET_FILE}."
    exit 1
}

echo "Publishing ${ARTIFACT} to Ansible Galaxy..."

ansible-galaxy collection publish $ARTIFACT --api-key $(cat $SECRET_FILE)