#!/usr/bin/env bash

vdecr() {
  unset IFS

  if [[ -n "$1" ]]; then
    if [[ -f "$1" ]]; then

      if [[ $(head -n1 "$1") == "\$ANSIBLE_VAULT;1.1;AES256" ]]; then
        cat "$1" | ansible-vault decrypt --vault-password-file ~/.vault-pass 2> /dev/null
        return 0
      fi
      printf 'Reading vault values from file...\n\n'
      local parsing=0
      local result=""
      local name=""
      local blue=$(tput setaf 4)
      local discard=$(tput sgr0)
      for line in $(cat $1); do
        if [[ $(echo "$line" | grep -c "\!vault") -gt 0 ]] && [[ $parsing -eq 0 ]]; then
          parsing=1
        elif [[ $parsing -eq 1 ]] && [[ $( echo $line | grep -c ":") -eq 0 ]]; then
          result=$(printf "${result}\n${line}")
        else
          if [[ $result != "" ]]; then
            printf "\n\n${blue}$name${discard}\n"
            printf "$result" | vdecr
            name=""
            result=""
            parsing=0
          fi
        fi
        if  [[ $( echo "$line" | grep -c ":") -eq 1 ]]; then
          name="$line"
        fi
      done
      return 0
    fi
    local str="$1"
  elif [[ ! -t 0 ]]; then
    local str=$(cat)
  else
    printf 'Interactive mode. Paste encrypted string and press Ctrl-D two times to confirm.\n'
    local str=$(cat)
    printf '\n'
  fi

  printf -- "$str" | sed 's/ /\n/g' | \
  sed '/---\|^.*:\|\!vault\||\|^$/d' | \
  ansible-vault decrypt --vault-password-file ~/.vault-pass 2> /dev/null
  printf '\n'
}

vdecr $1
