#!/bin/bash

function unifi_update_cert(){
    NAMESPACE=unifi
    DEPLOYMENT=unifi
    P12_TEMP=/tmp/p12_temp
    ALIAS=unifi
    PASSWORD=aircontrolenterprise
    KEYSTORE=/unifi/data/keystore
    SIGNED_CRT=/etc/letsencrypt/tls.crt
    CHAIN_FILE=/etc/letsencrypt-pem/isrgrootx1.pem
    PRIV_KEY=/etc/letsencrypt/tls.key

    POD=$(kubectl -n "$NAMESPACE" get pod --selector=app.kubernetes.io/name=unifi --template "{{range .items}}{{.metadata.name}}{{\"\n\"}}{{end}}")


    kubectl -n "$NAMESPACE" exec -it "$POD" -- bash -c "keytool -delete -alias ${ALIAS} -keystore ${KEYSTORE} -deststorepass ${PASSWORD}"
    kubectl -n "$NAMESPACE" exec -it "$POD" -- bash -c "openssl pkcs12 -export \
            -in ${CHAIN_FILE} \
            -in ${SIGNED_CRT} \
            -inkey ${PRIV_KEY} \
            -out ${P12_TEMP} -passout pass:${PASSWORD} \
            -name ${ALIAS}"
    kubectl -n "$NAMESPACE" exec -it "$POD" -- bash -c "keytool -delete -alias ${ALIAS} -keystore ${KEYSTORE} -deststorepass ${PASSWORD}"
    kubectl -n "$NAMESPACE" exec -it "$POD" -- bash -c "keytool -importkeystore \
            -srckeystore ${P12_TEMP} -srcstoretype PKCS12 \
            -srcstorepass ${PASSWORD} \
            -destkeystore ${KEYSTORE} \
            -deststorepass ${PASSWORD} \
            -destkeypass ${PASSWORD} \
            -alias ${ALIAS} -trustcacerts"

    kubectl -n "$NAMESPACE" scale deployment "$DEPLOYMENT" --replicas=0
    echo "sleeping 20 sec"
    sleep 20
    kubectl -n "$NAMESPACE" scale deployment "$DEPLOYMENT" --replicas=1
}
