#! /bin/bash


findup ()
{
  DIR='..'
  DIRTEST=$( cd $DIR ; pwd )

  while [[ "$DIRTEST" != "/" ]]; do
    DIR="$DIR/.."
    DIRTEST=$( cd $DIR ; pwd )

    if [[ -d "$DIR/$1" ]]; then
      echo "$DIR/$1"
      return 0
    fi
  done

  # Failed to find
  return 1
}

if [ ! -f terragrunt.hcl ]; then
  echo "ERROR: No terragrunt.hcl in this directory. Aborting."
  exit 1
fi

GITSOURCE=$( cat terragrunt.hcl | egrep -v '^ *#' | egrep 'source *= *"git@' )

if [ "$GITSOURCE" == "" ]; then
  echo "ERROR: No source from Git detected. Aborting."
  exit 2
fi

# Strip off source = and quotes
GITSOURCE=$( echo "$GITSOURCE" | sed -E 's/.*"([^"]+)".*/\1/' )

# Strip off any ?ref= if it's there
GITSOURCE=$( echo "$GITSOURCE" | sed -E 's/\?.*$//' )

# Thanks to terragrunt needing that magic // construct
GITSOURCE_REPO=$( echo "$GITSOURCE" | sed -E 's#//.*$##' )
GITSOURCE_PATHINREPO=$( echo "$GITSOURCE" | sed -E "s#.*//##" )

BARE_REPONAME=$( basename "$GITSOURCE_REPO" .git )

LOCALPATH=$( findup "$BARE_REPONAME" )
if [[ "$LOCALPATH" == "" ]]; then
  echo "ERROR:  No $BARE_REPONAME in any parent directory"
  exit 1
fi

NEWPATH="$LOCALPATH//$GITSOURCE_PATHINREPO"
echo Substituting \'$GITSOURCE\' with \'$NEWPATH\'

if [ ! -f .terraform.lock.hcl ]; then
  echo "No providers lock (.terraform.lock.hcl) found  in this directory. Creating..."
  terragrunt providers lock -platform=darwin_amd64 -platform=linux_amd64 -platform=windows_amd64 -platform=linux_arm64 --terragrunt-source $NEWPATH
  RC=$?
  if [[ $RC != 0 ]]; then
    read -p "ERROR: Failed to generate providers file. Apply anyway? [yN] " -n 1 -r
    echo ""
    if [[ ! $REPLY =~ ^[Yy]$ ]]
    then
      echo Exiting...
      exit 4
    fi
  fi
fi

# Test locally
# the double // is intentional! Terragrunt uses this to determine the root of the modules repository.
terragrunt $* --terragrunt-source $NEWPATH
