#!/bin/bash

if [ $# -ne 1 ]; then
    echo "Usage: $0 RELEASE_TAG"
    exit 1
fi

RELEASE_TAG="$1"
BRANCH_NAME="index-${RELEASE_TAG}"
COMMIT_MESSAGE="This PR updates index.yaml for ${RELEASE_TAG}. Automatically generated by make update-helm-plugin-repo."
PR_TITLE="🌱 Update helm chart index.yaml to ${RELEASE_TAG}"
PR_DESCRIPTION=$(printf "**What this PR does / why we need it:**\n\nThis PR updates index.yaml for ${RELEASE_TAG}.\n\nAutomatically generated by \`make update-helm-plugin-repo\`.")

# Checkout index-${RELEASE_TAG} branch
git checkout -b "${BRANCH_NAME}"

# Add files to commit
git add plugins/clusterctl-operator.yaml index.yaml

# Commit changes with appropriate message
git commit -m "${COMMIT_MESSAGE}"

# Push changes to origin
git push origin "${BRANCH_NAME}"

if ! command -v gh &> /dev/null
then
    echo "GitHub CLI (gh) is not installed."
    echo "Please open a pull request with the following details:"
    echo "Title: $PR_TITLE"
    echo -e "Description: \n$PR_DESCRIPTION"
    exit 0
fi

# Open a PR with title and description
gh pr create --title "${PR_TITLE}" --body "${PR_DESCRIPTION}"
