#!/bin/sh
set -x

# Modified from Dustin Ingram (@di)'s python-disposable-email-domains project
# (License in COPYING)

# Clone the source repository
rm -rf source_data
git clone https://github.com/Mottie/github-reserved-names.git source_data && \
# Create what would be generated by source_data
python3 bin/parse_source_data > github_reserved_names.py && \

# See if anything has changed
git diff --exit-code

CHANGES=$?

if [ -z "${TEST_ONLY}" ] && [ $CHANGES != 0 ]; then
    # Git setup
    git config --global user.email 'Julian@users.noreply.github.com'
    git config --global user.name "Julian Berman"
    git remote set-url origin "https://x-access-token:$GITHUB_TOKEN@github.com/Julian/github-reserved-names.git"

    # Add changes, push and make a PR
    git checkout -b update-source-data
    git commit -am "Pull in changes to the upstream source data."
    git push -f origin HEAD
    curl --show-error --fail -u "x-access-token:$GITHUB_TOKEN" --data '{"title": "'"Update source data"'", "head": "'"update-source-data"'", "base": "main"}' https://api.github.com/repos/Julian/github-reserved-names/pulls
    exit $?
else
    exit $CHANGES
fi
