#!/bin/bash
function ah(){
local opts=$(cat << EOF
aws.sshkeygen.pem  :: $(printf "ssh-keygen -m PEM -t rsa -b 2048 -f '%s.pem' -q -N '' && chmod 400 '%s.pem'" "${1}" "${1}")
aws.sshkeygen.pub  :: $(printf "ssh-keygen -f '%s' -y" "${1}")
aws.instcon        :: $(printf "aws ec2-instance-connect --region eu-central-1 ssh --instance-id %s" "$(xsel -bo | dos2unix |  head -n 1 | tr -d '\n\r ')" )
aws.selProf        :: awsProfileSelect
aws.store          :: awsStoreSecrets
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

  selOpt=$( echo "${selOpt}" | sed  -E 's/(^.*)[ ]*::[ ]*(.*$)/\2/g' )

  echo ">>>>>>> ${selOpt}"
  history -s "${selOpt}"
  history -s "ah"
  eval "${selOpt}"
}

function awscliMFA(){
  expiration=''
  unset $(env | grep -E '^AWS' | grep -v 'PROFILE' | cut -d '=' -f 1)

  local aws_mfa_serial=""
  local aws_profile=""
  local aws_role_arn=""
  local aws_source_profile=""

  aws_profile=$(cat ~/.aws/config | grep -E '^\[profile' | sed -E 's|(^\[profile )(.*)(\].*)|\2|g' | fzf)
  aws_source_profile=$(aws configure --profile "${aws_profile}" get source_profile | sed -E 's|(.*)(_MFA)|\1|g')
  aws_role_arn=$(aws configure --profile "${aws_profile}" get role_arn)

  if [ "${aws_source_profile}" == "" ]; then
    aws_source_profile="${aws_profile}"
  fi

  aws_mfa_serial=$(aws configure  --profile "${aws_source_profile}" get mfa_serial)

  if [ "${aws_role_arn}" == "" ]; then
    local content=$(
        echo "[${aws_profile}_MFA]"
        while read  -r line; do
            cmd=''
            key=$(echo $line | cut -d ':' -f 1                          )
          value=$(echo $line | cut -d ':' -f 2-99 | sed -E 's|^[ ]*||g' )

            if [ "${key}" == 'AccessKeyId'     ];then echo "aws_access_key_id = ${value}"
          elif [ "${key}" == 'SecretAccessKey' ];then echo "aws_secret_access_key = ${value}"
          elif [ "${key}" == 'SessionToken'    ];then echo "aws_session_token = ${value}"
          fi
        done < <(aws sts get-session-token --profile "${aws_source_profile}" --serial-number "${aws_mfa_serial}" --output yaml --token-code "${1}")
    )

    content=$(printf "##>>> %s\n%s\n##<<< %s" "${aws_profile}_MFA" "${content}" "${aws_profile}_MFA")

    echo "${content}"
    echo "${content}" | xsel -bi

    sed -i '/^##>>> '"${aws_profile}_MFA"'/,/^##<<< '"${aws_profile}_MFA"'/{/^##>>> '"${aws_profile}_MFA"'/!{/^##<<< '"${aws_profile}_MFA"'/!d}}' ~/.aws/credentials
    while read  -r line; do
      sed -i -E 's|^##<<< '"${aws_profile}_MFA"'$|'"${line}"'\n##<<< '"${aws_profile}_MFA"'|g' ~/.aws/credentials
    done < <(echo "${content}" | sed '1d')
    sed -i -e '/##<<< '"${aws_profile}_MFA"'/{n;d}' ~/.aws/credentials
  fi

  if [ "${aws_role_arn}" != "" ]; then
    local content=$(
        echo "[${aws_profile}]"
        while read  -r line; do
            cmd=''
            key=$(echo $line | cut -d ':' -f 1                          )
          value=$(echo $line | cut -d ':' -f 2-99 | sed -E 's|^[ ]*||g' )

            if [ "${key}" == 'AccessKeyId'     ];then echo "aws_access_key_id = ${value}"
          elif [ "${key}" == 'SecretAccessKey' ];then echo "aws_secret_access_key = ${value}"
          elif [ "${key}" == 'SessionToken'    ];then echo "aws_session_token = ${value}"
          fi
        done < <(aws sts assume-role  --profile "${aws_source_profile}" --role-arn "${aws_role_arn}" --role-session-name admin --serial-number "${aws_mfa_serial}" --output yaml --token-code "${1}")
    )

    content=$(printf "##>>> %s\n%s\n##<<< %s" "${aws_profile}" "${content}" "${aws_profile}")

    echo "${content}"
    echo "${content}" | xsel -bi

    sed -i '/^##>>> '"${aws_profile}"'/,/^##<<< '"${aws_profile}"'/{/^##>>> '"${aws_profile}"'/!{/^##<<< '"${aws_profile}"'/!d}}' ~/.aws/credentials
    while read  -r line; do
      sed -i -E 's|^##<<< '"${aws_profile}"'$|'"${line}"'\n##<<< '"${aws_profile}"'|g' ~/.aws/credentials
    done < <(echo "${content}" | sed '1d')
    sed -i -e '/##<<< '"${aws_profile}"'/{n;d}' ~/.aws/credentials
  fi
}

function awsProfileSelect(){
  selection=$(
    while read  -r line; do
        clearName=$(echo "${line}" | cut -d ' ' -f 1)
      accountName=$(echo "${line}" | cut -d ' ' -f 2)

      printf "%-30s %s\n" "${clearName}" "${accountName}"
    done < <(cat ~/.aws/config | grep -E '^\[profile.*##' | sed -E 's|(^[profile[ ]*)(.*)(\].*)(.*##)(.*)|\5 \2|g')
  )

  selection=$(echo "${selection}" | fzf)
  selection=$(echo "${selection}" | tr -s ' ' | cut -d ' ' -f 2)
  echo "${selection}"

  export AWS_PROFILE="${selection}"
}

function awsStoreSecrets(){
       hit="0"
   content="$(xsel -bo | dos2unix )"

  headline="$(printf "${content}" |  head -n 1)"

  collector=''

  while read line; do
    ##echo ">>>${headline}<<<  <<<$(printf "${line}")>>>  ===${hit}==="

      if [ 1 == 0                                            ]  ; then echo 'huhu' ;
    elif [ "${headline}" == "${line}" ] && [ "${hit}" == "0" ]  ; then hit='1' ; collector=$(printf "${collector}%s" "$(printf "${content}")\n") ;
    elif [ "${line}" == ""            ] && [ "${hit}" == "1" ]  ; then hit='0'     ;
    fi

    if [ "${hit}" == "0" ]; then collector=$(printf "${collector}%s" "${line}\n"); fi
  done < <(cat ~/.aws/credentials | dos2unix)

  printf "${collector}" >~/.aws/credentials
}
