#! /bin/bash
# 
# Do a more sane apply-all via terragrunt

function argparse {
  PARAMS=""
  ENVS=()
  while (( "$#" )); do
    case "$1" in
      -h|--help)
        echo Usage: $0 '[-l|--local] [-t|--test] [-s|--skipqualys] [ENVFLAGS] [-d|--debug]'
        echo "       where ENVFLAGS is one or more of --envprod, --envcommon, --envtest, or --envall. --envall is the default."
        exit 1
        ;;
      -t|--test)
        TESTING="/bin/echo TESTING: "
        shift
        ;;
      -l|--local)
        LOCAL="--local"
        shift
        ;;
      -n|--notlocal)
        NOTLOCAL="--notlocal"
        shift
        ;;
      -d|--debug)
        >&2 echo debug: Enabling debugging..
        DEBUG=1
        debugstr="--debug"
        shift
        ;;
      --envall)
        ENVS+=("test")
        ENVS+=("common")
        ENVS+=("prod")
        shift
        ;;
      --envtest)
        ENVS+=("test")
        shift
        ;;
      --envcommon)
        ENVS+=("common")
        shift
        ;;
      --envprod)
        ENVS+=("prod")
        shift
        ;;
      -s|--skipqualys)
        SKIPQUALYS="--skipqualys"
        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
  if [[ ${#ENVS[@]} == 0 ]]; then
    # Default to all environments
    ENVS+=("test")
    ENVS+=("common")
    ENVS+=("prod")
  fi
  # 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 [[ $SHORT_PWD != "xdr-terraform-live" ]]; then
  read -p "WARNING! Not running from 'xdr-terraform-live'. PWD is $SHORT_PWD. Continue anyway? [Y/n]? " -n 1 -r
  echo ""
  if [[ $REPLY =~ ^[Nn]$ ]]
  then
    echo Exiting...
    exit 1
  fi
fi

[[ $DEBUG == 1 ]] && >&2 echo debug: ENVS=${ENVS[*]}
for e in ${ENVS}; do
  pushd $e > /dev/null
  for p in aws aws-us-gov; do
    pushd $p > /dev/null
    for a in $(find . -type d -mindepth 1 -maxdepth 1); do
      pushd $a > /dev/null

      echo ""
      echo ""
      echo "*************************************************************************************"
      echo "Beginning environment '$e', partition '$p', account '$a'"
      echo "*************************************************************************************"
      echo ""
      echo ""

      if [[ -f UNUSED.ACCOUNT ]]; then
        echo -- This account is marked as unused. Skipping...
        popd > /dev/null
        continue
      fi

      if [[ -f UNMANAGED.ACCOUNT ]]; then
        echo -- This account is marked as unmanaged. Skipping...
        popd > /dev/null
        continue
      fi

      EXITCODE=1 # Assume error
      if [[ $DEBUG == 1 ]]; then
        echo debug: Would run: terragrunt-apply-all $TESTING $LOCAL $NOTLOCAL $debugstr $SKIPQUALYS
        EXITCODE=$?
      else
        terragrunt-apply-all $TESTING $LOCAL $NOTLOCAL $DEBUG $SKIPQUALYS
        EXITCODE=$?
      fi

      if [[ $EXITCODE != 0 ]]; then
        # Prompt to continue after each module. Easier than ctrl-c...
        read -p "Terragrunt failed for environment '$e', partition '$p', account '$a'.. Continue to next account [Y/n]? " -n 1 -r
        echo ""
        if [[ $REPLY =~ ^[Nn]$ ]]
        then
            echo Exiting...
            exit 1
        fi
      fi

      popd > /dev/null
    done
    popd > /dev/null
  done
  popd > /dev/null
done

echo Finished.
exit 0
