#! /bin/bash
# 
# Run from an account directory to update all the child directory's references.
# This should be run before or after `terragrunt-local`

function argparse {
  PARAMS=""
  while (( "$#" )); do
    case "$1" in
      -n|--newtag)
        if [ -n "$2" ] && [ ${2:0:1} != "-" ]; then
          NEWTAG=$2
          shift 2
        else
          echo "Error: Argument for $1 is missing" >&2
          exit 1
        fi
        ;;
      -h|--help)
        echo Usage: $0 '[-t|--test] [-d|--debug] -n|--newtag NEWTAG'
        exit 0
        ;;
      -t|--test)
        TESTING="/bin/echo TESTING: "
        shift
        ;;
      -d|--debug)
        >&2 echo debug: Enabling debugging..
        DEBUG=1
        shift
        ;;
#      -p|--only-path)
#        if [ -n "$2" ] && [ ${2:0:1} != "-" ]; then
#          ONLY_PATH=$2
#          shift 2
#        else
#          echo "Error: Argument for $1 is missing" >&2
#          exit 1
#        fi
#        ;;
      -*|--*=) # unsupported flags
        echo "Error: Unsupported flag $1" >&2
        exit 1
        ;;
      *) # preserve positional arguments
        PARAMS="$PARAMS $1"
        shift
        ;;
    esac
  done
  # set positional arguments in their proper place
  eval set -- "$PARAMS"
}

# Main
argparse $*

SHORT_PWD=$( basename ${PWD}  )
PARENT_PWD=$( basename $( cd .. && pwd ) )
[[ $DEBUG == 1 ]] && >&2 echo debug: PWD=$PWD
[[ $DEBUG == 1 ]] && >&2 echo debug: SHORT_PWD=$SHORT_PWD

# Sanity Checking
if [[ "$NEWTAG" == "" ]]; then
  >&2 echo Error: Parameter \'--newtag\' is required.
  exit 5
fi

if [[ $SHORT_PWD =~ ^[0-9]{3}-.* ]]; then
  if [[ $SHORT_PWD == "000-skeleton" ]]; then
    read -p "Are you sure you wish to update the SKELETON directory [y/N]? " -n 1 -r
    echo ""
    if [[ $REPLY =~ ^[Yy]$ ]]
    then
      echo Continuing...
    else
      echo Exiting...
      exit 10
    fi
  else
    >&2 echo Error: We appear to be in a module directory. Please run from the account directory you wish to update. Exiting...
    exit 2
  fi
fi

if [[ $NEWTAG =~ v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  [[ $TESTING ]] && >&2 echo debug: Newtag $NEWTAG is valid format.
else
  >&2 echo Error: Invalid format for new tag. \"$NEWTAG\" must be of format v1.2.3
  exit 6
fi

for i in `find . -maxdepth 2 -name "terragrunt.hcl"`; do
  echo ======= Processing $i
  ${TESTING} sed -E -i .bak 's/ref=v[0-9]+.[0-9]+\.[0-9]+"$/ref='${NEWTAG}'"/' $i
done


