#! /bin/bash
#
# Updates the local environments from the skeleton directory
# Parse Arguments. This is a standard parser.
# 
# At present, should be fun from a ###-module directory
# Future work:
#   * Run it from the account directory
#   * Specify only one path

function argparse {
  PARAMS=""
  while (( "$#" )); do
    case "$1" in
      -h|--help)
        echo Usage: $0 '[-t|--test] [-d|--debug]'
        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"
}

function cmpfile {
  # Returns 0 if they're the same (and should not be copied)
  # Returns 1 if they're different (and should be copied)
  SRCFILE=$1
  DSTFILE=$2

  if [[ ! -f $SRCFILE ]]; then
    [[ $DEBUG ]] && echo Warning: $SRCFILE does not exist. Not copying...
    return 0
  fi

  if [[ ! -f $DSTFILE ]]; then
    echo Warning: $DSTFILE does not exist. Copying regardless...
    return 1
  fi

  diff $SRCFILE $DSTFILE > /dev/null 2> /dev/null
  if [[ $? == 0 ]]; then
    [[ $DEBUG ]] && >&2 echo debug: $SRCFILE and $DSTFILE are same
    return 0
  else
    [[ $DEBUG ]] && >&2 echo debug: $SRCFILE and $DSTFILE are different
    return 1
  fi
}

# 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
[[ $DEBUG == 1 ]] && >&2 echo debug: PARENT_PWD=$PARENT_PWD

# Sanity checking
if [[ $SHORT_PWD == "000-skeleton" ]]; then
  >&2 echo Error: Cannot run from skeleton directory. Exiting...
  exit 1
fi

if [[ ! $SHORT_PWD =~ ^[0-9]{3}-.* ]]; then
  >&2 echo Error: Please run from the module directory you wish to update. Exiting...
  exit 2
fi

SRC=../../../../000-skeleton/${SHORT_PWD}

if [[ ! -d ${SRC} ]]; then
  >&2 echo Error: ${SRC} does not exist. Cannot copy.
  exit 3
fi

cmpfile ${SRC}/README.md ./README.md
if [[ $? != 0 ]]; then
  echo Copying readme from skeleton...
  ${TESTING} cp -vf ${SRC}/README.md .
else
  echo Not copying readme.
fi

cmpfile ${SRC}/terragrunt.hcl ./terragrunt.hcl
if [[ $? != 0 ]]; then
  echo Copying terragrunt.hcl from skeleton...
  ${TESTING} cp -vf ${SRC}/terragrunt.hcl .
else
  echo Not copying terragrunt.
fi
