#!/bin/bash
#
# Deploy Puppet changes whenever new stuff is pushed.
#

# Reset environment so we can use git
unset GIT_INDEX_FILE
unset GIT_DIR

# Set a sane umask. This is a shared environment so needs to be group writeable.
# The default umask is 0022 and we can't be sure how users may have set theirs.
umask 0002

while read oldref newref name
do
    # Check the branch name used.
    # Ensure that only characters permitted in Puppet environment names are used.
    # See: https://docs.puppet.com/puppet/3.8/reference/lang_reserved.html#environments
    branch=${name##refs/heads/}
    # This is checked in deploy-puppet-environment, but we might as well check here too.
    if ! [[ ${branch} =~ ^[a-z0-9_]+$ ]]; then
      echo "Branch names in this repo should be valid Puppet Environment names."
      echo "Valid names match the regex ^[a-z0-9_]+$."
      echo "We won't create an environment from this branch."
      exit 1
    fi

    # Cater for branch removal, with a sanity check for master
    # a newref of 0000000000000000000000000000000000000000 indicates branch deletion
    if [[ ${newref} =~ ^0+$ ]]; then
      # This is checked in deploy-puppet-environment, but we might as well check here too.
      if [[ "${branch}" == "master" ]]; then
        echo "Looks like you're trying to delete the master branch - not going to do that."
        echo "You might want to check what has happened."
        exit 1
      else
        sudo /data/mysociety/bin/deploy-puppet-environment -d -b $branch
      fi
    else
      sudo /data/mysociety/bin/deploy-puppet-environment -b $branch -r $newref
    fi
done
