#!/usr/bin/env /lib/runit/invoke-run

. /etc/ark/monitor-config

if [ -z "$ARK_FQDN" ]; then
    echo "ERROR: ARK_FQDN unset, can't renew certificates"
    exit 1
fi

X509_CERT="/etc/ark/ssl/$ARK_FQDN.crt"
X509_KEY="/etc/ark/ssl/$ARK_FQDN.key"

if [ ! -e "$X509_CERT" ]; then
    echo "ERROR: Missing certificate $X509_CERT"
    exit 1
fi

if [ ! -e "$X509_KEY" ]; then
    echo "ERROR: Missing key $X509_KEY"
    exit 1
fi

echo "Starting certificate renewal checks..."
while true; do
    if /usr/bin/step certificate needs-renewal "$X509_CERT"; then
        echo $(date) "Renewing certificates..."
        # renew x509 certificate
        /usr/bin/step ca renew \
            --force \
            --mtls=false \
            "$X509_CERT" \
            "$X509_KEY"

        # renew ssh user certificate
        /usr/bin/step ssh certificate \
            --force \
            --insecure \
            --no-password \
            --no-agent \
            --x5c-cert "$X509_CERT" \
            --x5c-key "$X509_KEY" \
            "$ARK_FQDN" \
            /etc/ark/ssh/ssh_user_ecdsa_key

        # renew ssh host certificate
        /usr/bin/step ssh certificate \
            --host \
            --force \
            --insecure \
            --no-password \
            --no-agent \
            --x5c-cert "$X509_CERT" \
            --x5c-key "$X509_KEY" \
            "$ARK_FQDN" \
            /etc/ark/ssh/ssh_host_ecdsa_key
    fi

    # TODO add some jitter
    sleep 3600
done
