#!/bin/bash
set -e
#export AKVNAME=akv-k8s
export AKVNAME="akv-prd-kubernetes"
export CH=nsptracker
export AKSENVIRONMENT=prd
  count=0
## echo "kv-$CH-$AKSENVIRONMENT-"

#space seperated
for AKVNAME in akv-prd-kubernetes akv-k8s
  do
  ##filter for kv-<ch>-<env>
  certNames=()
  # list all certificates
  certNames+=( $(az keyvault secret list --vault-name $AKVNAME --query "[?contains(id,'/kv-') && attributes.enabled && contentType=='application/x-pem-file'].id" -o tsv |\
                awk -F'/secrets/' '{print $2}' |\
                grep "^kv-$CH-$AKSENVIRONMENT-\|^kv-$CH-all-\|^kv-all-$AKSENVIRONMENT\|^kv-all-all\|^kv-") )
  #
  rc=$?
  if [[ $rc != 0 ]]; then
      echo "#$0: Can't find secrets, start with kv-"
      exit 1
  else
      echo "#$0: az keyvault found $(echo \"${certNames[@]}\" | wc -w )"
  fi

  # check array is empty
  if [ ! "${#certNames}" ]; then echo "$0: Error !!! Double check keyvault certificates, start with kv-$CH-$AKSENVIRONMENT in keyvault $AKVNAME"; exit 1; fi

  echo "#$0: \"$AKVNAME\" cert names: ${certNames[@]}"
  for certName in "${certNames[@]}";
  do
    echo
    count=$(($count + 1))
    echo "$count: ak keyvault download --vault-name $AKVNAME --name \"$certName\""
    rm  /tmp/$certName-* || true
    az keyvault secret download --name $certName \
                                --vault-name $AKVNAME \
                                --file /tmp/$certName-privateKey.pem

    az keyvault certificate download  --vault-name $AKVNAME \
                                      --name $certName \
                                      --file /tmp/$certName-cert.pem

    # az keyvault secret download --name $certName \
    #                             --vault-name $AKVNAME \
    #                             --encoding base64 \
    #                             --file /tmp/$certName-privateKey.pfx

    #./az_script-20helper-split-pem.py /tmp/$certName-privateKey.pem /tmp/$certName-split
    docker run --rm --name test \
    -v "$PWD":/usr/src/myap -w /usr/src/myap \
    -v /tmp:/tmp \
    --env certName=$certName \
    --env USER_ID=$(id -u ${USER}) \
    --env GROUP_ID=$(id -g ${USER}) \
    python:3.7-alpine \
      sh -c 'python -m pip install pem ; python az_script-20helper-split-pem.py /tmp/$certName-privateKey.pem /tmp/$certName-split ; chown --changes --silent ${USER_ID}:${GROUP_ID} /tmp/$certName-split* '

  ls -l /tmp/$certName-*
  done

done
