#!/bin/bash
export TF_PLUGIN_CACHE_DIR="${HOME}/.terraform.d/plugin_cache_dir"
cp ~/.terraform.d/credentials.tfrc.json.carglass ~/.terraform.d/credentials.tfrc.json

alias  terraform='tfdtct;~/.tfenv/bin/terraform'

alias      tf='terraform'
alias  tfdocs='/usr/local/bin/terraform-docs'
alias     tff='read -p "terraform fmt --recursive (yes/*): " a; case $a in "yes") terraform fmt --recursive ;; *) echo "-- Nothing to do --";; esac'
alias     tfi='export TF_PLUGIN_CACHE_DIR="${HOME}/.terraform.d/plugin_cache_dir"; terraform init'
alias     tfp='find -type f -not -path '"'"'*/.terraform*'"'"' -not -path '"'"'*/.git*'"'"' | grep -E "\.tf$|\.y*ml$" | xargs -rI{} sed -i -e '"'"'/./,$!d'"'"' -e :a -e '"'"'/^\n*$/{$d;N;ba'"'"' -e '"'"'}'"'"' -e '"'"'$a\'"'"' '"'"'{}'"'"' ; terraform plan -no-color'
alias     tfv='terraform validate'
alias     tii='read -p "terraform init --recursive (yes/*): " a; case $a in "yes") find -type d | grep -E '/account.*head$' | xargs -rI{} find '{}' -type f | grep -E '\.tf$' | grep -Fv '.terraform' | sed -E "s|(.*/head)(/.*)|\1|g" | sort -u | xargs -rI{} bash -c "cd "'"{}"'" ; terraform init";; *) echo "-- Nothing to do --";; esac'
alias    tfaa='read -p "terraform apply --auto-approve (yes/*): " a; case $a in "yes") terraform apply --auto-approve ;; *) echo "-- Nothing to do --";; esac'

alias  tf_bucketuse="grep -EH '\b(bucket|key|region|profile)\b[ ]*=[ ]*\"|\"terraform_remote_state\"' *"
alias tf_resetstate='git status | grep -E '"'"'modified.*\.terraform\.lock\.hcl'"'"' | cut -d '"'"':'"'"' -f 2 | tr -s '"'"' '"'"' | sed -E '"'"'s| ||g'"'"' | xargs -rI{} bash -c "git reset -- '"'"'{}'"'"' ; git checkout -- '"'"'{}'"'"'"'

function th(){
local opts=$(cat << EOF
code       :q: . ______________
code       :q: find -type d | grep -E 'head$' | xargs -rI{} find '{}' -type f | grep -E '\.tf$' | grep -Fv '.terraform' | xargs -rI{} grep -E '\b(source|version)\b' {} | tr -s ' ' | sed -z 's|\n version = | \:\: |g' | sed -E 's| source = |##|g' | grep -E '^##' | sed -E 's|^##||g' | sort -u
code       :q: find -type d | grep -E 'head$' | xargs -rI{} find '{}' -type f | grep -E '\.tf$' | grep -Fv '.terraform' | xargs -rI{} grep -HE '\b(source|version)\b' {} | tr -s ' '
dck        :q: . ______________
dckpc      :q: docker run --rm -e "USERID=$(id -u):$(id -g)" -v $(pwd):/lint -w /lint precommit run -a
dckpc      :q: docker run -it --rm -v $(pwd):/lint -w /lint --entrypoint /bin/bash precommit -c "find . -type f -regex '.*\.tf$' -not -path '*/.terraform*' -not -path '*/.git*' | sed -E 's|(.*)(\/.*)|\1|g' | sort -u | xargs -rI{} bash -c 'cd "{}" ; terraform-docs asciidoc . >tfdocs.adoc'"
dpr        :q: . ______________
dprfmt     :q: find . -type f -regex '.*\.tf\$' -not -path '*/.terraform*' -not -path '*/.git*' | sed -E 's|(.*)(\/.*)|\1|g' | sort -u | xargs -rI{} bash -c 'cd "{}" ; echo ">>>> \${PWD}" ; terraform fmt'
dprval     :q: find . -type f -regex '.*\.tf\$' -not -path '*/.terraform*' -not -path '*/.git*' | sed -E 's|(.*)(\/.*)|\1|g' | sort -u | xargs -rI{} bash -c 'cd "{}" ; echo ">>>> \${PWD}" ; terraform fmt ; terraform validate'
dprxx      :q: find . -type f -regex '.*\.tf\$' -not -path '*/.terraform*' -not -path '*/.git*' | sed -E 's|(.*)(\/.*)|\1|g' | sort -u | xargs -rI{} bash -c 'cd "{}" ; echo ">>>> \${PWD}" ; ${1}'
oth        :q: . ______________
othca      :q: find . | grep -E '\.terraform$|/terraform\.|.terraform.*' | xargs -rI{} rm -Rfv '{}'
othchm     :q: find -type d | xargs -rI{} chmod 755 '{}' ; find -type f | xargs -rI{} chmod 644 '{}'
othd2u     :q: find . -type f -regex '.*\.tf$' -not -path '*/.terraform*' -not -path '*/.git*' | sed -E 's|(.*)(\/.*)|\1|g' | sort -u | xargs -rI{} bash -c 'cd "{}" ; echo ">>>> ${PWD}" ; dos2unix *'
othmstcnt  :q: find . -type f -regex '.*\.tf$' -path '*/head*' -not -path '*/.terraform*' -not -path '*/.git*' | sort -u | xargs -rI{} grep -EH "^" '{}' >masterAllCnt.txt
othsstcnt  :q: find -type f | grep -F 'state.json' | sort -u | xargs -rI{} grep -EH '^' '{}' >superState.txt
othtar     :q: tar -czvf t_bin.tgz \$(find -type d | grep -E .terraform\$)
plygrd     :q: . ______________
plygrdbak  :q: ls -1 | grep -E '\.tf$' | sed -E 's|\.tf$||g' | xargs -rI{} mv '{}.tf' '{}.bak'
plygrdyml  :q: echo "${1}" | xargs -rI{} bash -c "sed -i -E 's|            |  |g' '{}' ; sed -i -E 's|\"||g' '{}' ; sed -i -E 's|(^[ ]*\+ )([a-zA-Z0-9\-_]*)([ ]*= <<-EOT)|\2:|g' '{}' ; sed -i -E '/^[ ]*EOT/d' '{}'"
prec       :q: . ______________
precrun    :q: pre-commit run -a
prectfd    :q: find . -type f -regex '.*\.tf$' -not -path '*/.terraform*' -not -path '*/.git*' | sed -E 's|(.*)(\/.*)|\1|g' | sort -u | xargs -rI{} bash -c 'cd "{}" ; terraform-docs asciidoc . >tfdocs.adoc'
tf         :q: . ______________
tfaply01   :q: echo '' >plan.txt ; terraform plan -no-color -lock=false 2>&1 | tee plan.txt
tfaply01nr :q: echo '' >plan.txt ; terraform plan -no-color -refresh=false -lock=false 2>&1 | tee plan.txt
tfaply02   :q: cat plan.txt | sort -u | grep -aE '^[ ]{2}#|^Plan'
tfaply02   :q: cat plan.txt | grep -aE '(^[ ]*(~|\+|-|#))|^Plan'
tfaply03   :q: terraform apply tfplan
tfaply05   :q: cp plan.txt plan.bak ; sed -i  '0,/Changes to Outputs:/d' plan.txt
tfaply05   :q: cp plan.txt plan.bak ; sed -i  '0,/Terraform used/d' plan.txt
tffmt      :q: git status | grep -E '\.tf$' | grep -E 'modified|new file' | tr -s ' ' | cut -d ':' -f 2 | xargs -rI{} bash -c 'if [ "{}" != "" ]; then terraform fmt "{}"; fi'
tfimpwp    :q: while true; do terraform plan -no-color -refresh=false -lock=false; sleep 20; done
tfimpwv    :q: watch -n 3 'terraform validate'
tfplan     :q: cat plan.txt | sort -u | grep -E '^[ ]{2}#|^Plan' >plan_sect.txt
tfplan     :q: terraform plan -no-color | grep -E ' (#|~|\+|\-) |^Plan'
tfplan     :q: terraform plan -no-color | sort -u | grep -E '^[ ]{2}#|^Plan'
tfplangen  :q: if [ -f '${1}' ]; then  rm -v '${1}' ; fi ; terraform plan -refresh=false -generate-config-out='${1}'
tfsort     :q: . ______________
tfsort01   ::  sed -Ei "s|(^[data|module|resource|variable|import|moved])|###001\1|g" "${1}"; sed -Ei "N;s|\n|###002|g"
tfsort02   ::  sed -Ei "s|###001|\n|g"
tfsort03   ::  sed -Ei "N;s|\n||g"
tfsort04   ::  sed -Ei "s|###002|\n|g"
tfstte     :q: terraform show -no-color -json | yq -P >state.yaml
tfstte     :q: terraform state pull           | yq -P >state.yaml
tftarc     :q: tar -czvf '${1}.tgz' '${1}' && rm -Rf '${1}'
tftarx     :q: tar -xzvf '$(echo "${1}" | sed -E 's|\.tgz$||g').tgz'
EOF
)

  local selOpt=$(echo "${opts}" | grep -vE '^##' | nl -i1 -n'rz' -v0 -w3 | sort -ru | fzf)

  if [ "${selOpt}" == "" ]; then
    echo ">>>>>>> nothing selected, cancel ..."
    return
  fi

    mode=$( echo "${selOpt}" | sed  -E 's/(^.*)([ ]*)(:[a-z]?:)([ ]*)(.*$)/\3/g' )
  selOpt=$( echo "${selOpt}" | sed  -E 's/(^.*)([ ]*)(:[a-z]?:)([ ]*)(.*$)/\5/g' )

  case $mode in
    ":q:")
      echo ">>>>>>> ${selOpt}"
      history -s "${selOpt}"
      eval "${selOpt}"
      ;;
    *)
      echo ">>>>>>> ${selOpt} '$@'"
      history -s "${selOpt} '$@'"
      history -s "th '$@'"
      eval "${selOpt} '$@'"
      ;;
  esac
}

function tfdtct(){
    if [ 1 == 0 ]                                                                                         ; then echo 'huhu'                                                            ;

  ## ## -- AppsA Germany - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 3   | rev) == "aws_german_project"                      ] ; then tfenv use 1.9.0   ; export AWS_PROFILE=122217416383_AAPowerAdministrator ;

  ## ## -- AppsA Nuke  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "fsxontap"                                 ] ; then tfenv use 1.14.4  ; export AWS_PROFILE=122217416383_AAPowerAdministrator ;
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "nuke_csv"                                 ] ; then tfenv use 1.7.5   ; export AWS_PROFILE=122217416383_AAPowerAdministrator ;
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "nuke"                                     ] ; then tfenv use 1.7.5   ; export AWS_PROFILE=122217416383_AAPowerAdministrator ;

  ## ## -- Belron AT - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "account-bat-backup-prod"                  ] ; then tfenv use 1.8.5   ; export AWS_PROFILE=BAT_BACKUP_PROD_MFA               ;
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "account-bat-mangement-prod"               ] ; then tfenv use 1.8.5   ; export AWS_PROFILE=036446437541_BDE_AWS_FULL-ADMIN   ;

  ## ## -- Belron DE - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "account-bde-backup-prod"                  ] ; then tfenv use 1.7.5   ; export AWS_PROFILE=036446437541_BDE_AWS_FULL-ADMIN   ;
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "account-bde-buildtools-prod"              ] ; then tfenv use 1.14.8  ; export AWS_PROFILE=821263843247_BDE_AWS_FULL-ADMIN   ;
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "account-bde-login-prod"                   ] ; then tfenv use 1.7.5   ; export AWS_PROFILE=834490809680_BDE_AWS_FULL-ADMIN   ;
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "account-bde-main-crp"                     ] ; then tfenv use 1.14.8  ; export AWS_PROFILE=868393128331_BDE_AWS_FULL-ADMIN   ;
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "account-bde-main-dev"                     ] ; then tfenv use 1.14.8  ; export AWS_PROFILE=365628033575_BDE_AWS_FULL-ADMIN   ;
  ##elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "account-bde-main-prod"                    ] ; then tfenv use 1.7.5   ; export AWS_PROFILE=888075181356_BDE_AWS_FULL-ADMIN   ;
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "account-bde-main-prod"                    ] ; then tfenv use 1.14.8  ; export AWS_PROFILE=888075181356_BDE_AWS_FULL-ADMIN   ;
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "account-bde-main-uat"                     ] ; then tfenv use 1.14.8  ; export AWS_PROFILE=710117937344_BDE_AWS_FULL-ADMIN   ;
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "account-bde-management-prod"              ] ; then tfenv use 1.7.5   ; export AWS_PROFILE=807893708968_BDE_AWS_FULL-ADMIN   ;
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "account-bde-network-prod"                 ] ; then tfenv use 1.14.8  ; export AWS_PROFILE=310770523134_BDE_AWS_FULL-ADMIN   ;
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "account-bde-oracle-crp"                   ] ; then tfenv use 1.14.8  ; export AWS_PROFILE=668227157566_BDE_AWS_FULL-ADMIN   ;
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "account-bde-oracle-dev"                   ] ; then tfenv use 1.14.8  ; export AWS_PROFILE=441345502585_BDE_AWS_FULL-ADMIN   ;
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "account-bde-oracle-prod"                  ] ; then tfenv use 1.14.8  ; export AWS_PROFILE=817423156165_BDE_AWS_FULL-ADMIN   ;
  ##elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "account-bde-oracle-uat"                   ] ; then tfenv use 1.7.5   ; export AWS_PROFILE=215958754683_BDE_AWS_FULL-ADMIN   ;
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "account-bde-oracle-uat"                   ] ; then tfenv use 1.14.8  ; export AWS_PROFILE=215958754683_BDE_AWS_FULL-ADMIN   ;
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "account-bde-qlikview-prod"                ] ; then tfenv use 1.14.8  ; export AWS_PROFILE=341319228646_BDE_AWS_FULL-ADMIN   ;
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "account-bde-qlikview-uat"                 ] ; then tfenv use 1.14.8  ; export AWS_PROFILE=657103446090_BDE_AWS_FULL-ADMIN   ;
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "account-bde-sandbox-dev"                  ] ; then tfenv use 1.14.8  ; export AWS_PROFILE=563703158576_BDE_AWS_FULL-ADMIN   ;
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "account-bde-security-audit"               ] ; then tfenv use 1.14.8  ; export AWS_PROFILE=637423577158_BDE_AWS_FULL-ADMIN   ;
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "account-bde-shared-prod"                  ] ; then tfenv use 1.14.8  ; export AWS_PROFILE=305856399206_BDE_AWS_FULL-ADMIN   ;
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "account-bde-tools-prod"                   ] ; then tfenv use 1.14.8  ; export AWS_PROFILE=171713597515_BDE_AWS_FULL-ADMIN   ;
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "account-bde-workspace-prod"               ] ; then tfenv use 1.14.8  ; export AWS_PROFILE=339713055671_BDE_AWS_FULL-ADMIN   ;
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "account-bju-main-prod"                    ] ; then tfenv use 1.14.8  ; export AWS_PROFILE=999245401427_AdministratorAccess  ;
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "ebs-crp"                                  ] ; then tfenv use 1.3.5   ; export AWS_PROFILE=868393128331_BDE_AWS_FULL-ADMIN   ;
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "ebs-dev"                                  ] ; then tfenv use 1.3.5   ; export AWS_PROFILE=365628033575_BDE_AWS_FULL-ADMIN   ;
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "ebs-prod"                                 ] ; then tfenv use 1.3.5   ; export AWS_PROFILE=888075181356_BDE_AWS_FULL-ADMIN   ;
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "ebs-uat"                                  ] ; then tfenv use 1.3.5   ; export AWS_PROFILE=710117937344_BDE_AWS_FULL-ADMIN   ;
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "k8s-dev"                                  ] ; then tfenv use 1.14.8  ; export AWS_PROFILE=365628033575_BDE_AWS_FULL-ADMIN   ;
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "k8s-prod"                                 ] ; then tfenv use 1.14.8  ; export AWS_PROFILE=365628033575_BDE_AWS_FULL-ADMIN   ;
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "k8s-uat"                                  ] ; then tfenv use 1.14.8  ; export AWS_PROFILE=365628033575_BDE_AWS_FULL-ADMIN   ;
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "terraform-aws-account"                    ] ; then tfenv use 1.14.8  ; export AWS_PROFILE=365628033575_BDE_AWS_FULL-ADMIN   ;
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "terraform-aws-cassandra"                  ] ; then tfenv use 1.14.8  ; export AWS_PROFILE=365628033575_BDE_AWS_FULL-ADMIN   ;
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "terraform-aws-grc-ec2-oel-v610"           ] ; then tfenv use 1.14.8  ; export AWS_PROFILE=365628033575_BDE_AWS_FULL-ADMIN   ;
  elif [ $(echo "${PWD}" | rev | cut -d '/' -f 2   | rev) == "terraform-aws-group-appsassociate-admins" ] ; then tfenv use 1.14.8  ; export AWS_PROFILE=365628033575_BDE_AWS_FULL-ADMIN   ;


  fi
}

function tfi_deep() {
  startDir="${PWD}"

  while  IFS= read res; do
    targetDir="${startDir}/${res}"

    cmd=$(printf "cd \"%s\" ; terraform init -no-color -backend=false" "${targetDir}")
    echo "${cmd}"
    eval "${cmd}"
  done < <(find -type d | grep -E '/head$' | sort -u)

  cd "${startDir}"
}

function tfs_deep() {
  startDir="${PWD}"

  while  IFS= read res; do
    targetDir="${startDir}/${res}"

    cmd=$(printf "cd \"%s\" ; tf state pull >state.json" "${targetDir}")
    echo "${cmd}"
    eval "${cmd}"
  done < <(find -type d | grep -E '/head$' | sort -u)

  cd "${startDir}"
}
