#!/bin/bash
# No u, because sometimes I run over the end of our args and then test $1
set -eo pipefail

<<COMMENT
This script tries to create an autopatch branch named for the date,
then autopatch all of our Terraform dependencies to the latest modules
COMMENT

usage() {
    echo "Patches all our Terraform at once"
    echo $0
    exit 1
}

# So you really want GNU getopt here since it will let you parse long
# strings, but since we only have the one command just check for it.
case "${1}" in
    --)
        shift; break;;
    -h | --help)  # Implied -h
        usage
        ;;
esac

shift $((OPTIND-1))

# This formatter works on both OSX Monterey 12.3 and Ubuntu 20.04 as of 04/04/22
DATE=$(date +%s)
BRANCH=autopatch-${DATE?}

git checkout -b autopatch-${DATE?}

for terraform_lockfile in $(find . | grep .terraform.lock.hcl); do
    terraform_dir=$(dirname ${terraform_lockfile})
    pushd .
    cd ${terraform_dir}
    terraform init -upgrade
    popd
done


# https://stackoverflow.com/questions/5143795/how-can-i-check-in-a-bash-script-if-my-local-git-repository-has-changes
if [[ ! `git status --porcelain --untracked-files=no` ]]; then
    exit 0
fi

git add .
git commit -a -m "Autopatcher Terraform run for timestamp ${DATE?}"
git push --set-upstream origin ${BRANCH?}

PR_TITLE="Autopatcher Terraform run for timestamp ${DATE?}"

gh pr create \
    -t "${PR_TITLE?}" \
    --base main \
    --body "" \
    -R palolotech/palolo.com \
    --head ${BRANCH?}
