#!/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 dependencies
COMMENT

usage() { echo autopatch.sh [-f/--full]; 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.  
FULL_UPGRADE=0
while [ ! -z "$1" ]; do
    case "${1}" in
        -f | --full)
            FULL_UPGRADE=true
            ;;
		--)
			shift; break;;
        *)  # Implied -h
            usage
            ;;
    esac
	shift
done
set -u

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?}

# Recursively go get all latest dependencies
if [ "$FULL_UPGRADE" == true ]; then 
	pnpm update -rL
else
	pnpm update -r
fi
# Do not use a frozen lockfile
pnpm install
# If our linter tools get updated, so does our linting
pnpm format

# 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 run for timestamp ${DATE?}"
git push --set-upstream origin ${BRANCH?}
if [ "$FULL_UPGRADE" == true ]; then 
    PR_TITLE="Autopatcher run for timestamp ${DATE?} (Full)"
else
    PR_TITLE="Autopatcher run for timestamp ${DATE?}"
fi
gh pr create \
    -t "${PR_TITLE?}" \
    --base main \
    --body "" \
    -R palolotech/palolo.com \
    --head ${BRANCH?}
