#!/bin/bash

function get_key() {
    KEY=$1
    KEY_VAL=$(echo $KEY | sed 's/\./\\./g')
    kubectl get secret -o  jsonpath="{.data['${KEY_VAL}']}" istiod-tls -n istio-system > istiodsecret/${KEY}.b64
    base64 -d istiodsecret/${KEY}.b64 > istiodsecret/${KEY}
}

function create_target_certs() {
    pushd istiodsecret
    cp tls.crt ca-cert.pem
    cp tls.key ca-key.pem
    cp ca.crt root-cert.pem
    cat tls.crt ca.crt > cert-chain.pem
    popd
}


function create_target_secret() {
  pushd istiodsecret
  kubectl create secret generic cacerts -n istio-system \
      --from-file=ca-cert.pem \
      --from-file=ca-key.pem \
      --from-file=root-cert.pem \
      --from-file=cert-chain.pem --dry-run -o json > secret.yaml
  kubectl apply -f secret.yaml
  popd
}

mkdir -p istiodsecret/
rm -rf istiodsecret/**

get_key "ca.crt"
get_key "tls.crt"
get_key "tls.key"

create_target_certs
create_target_secret