#!/bin/bash

# restart or reload any processes that depend on a certificate

set -e -o pipefail

SSLDIR="${SSLDIR:-/etc/ark/ssl}"

usage() {
    echo "Usage: $0 certificate-hostname"
}


reload_kafka() {
    local listener=$1
    local cert=$2

    if [ ! -d /etc/kafka/ssl ] || [ ! -x /usr/bin/kafka-configs ]; then
        return
    fi

    echo "Reloading kafka"

    # concatenate the existing key and the new cert so java/kafka can use it
    cat <(step crypto key format \
            --pem \
            --pkcs8 \
            --no-password \
            --insecure \
            "$SSLDIR/$cert.key") \
        "$SSLDIR/$cert.crt" \
        > "/etc/kafka/ssl/$cert-combined.pem"

    #chown ark:ark "$SSLDIR/$cert-combined.pem"
    #chmod 0640 "$SSLDIR/$cert-combined.pem"

    # reload the listener to use the new credentials
    kafka-configs --bootstrap-server 127.0.0.1:9092 \
                  --command-config /etc/kafka/admin.properties \
                  --alter \
                  --entity-type brokers \
                  --entity-name 0 \
                  --add-config "listener.name.$listener.ssl.keystore.location=/etc/kafka/ssl/$cert-combined.pem"
}


reload_natp_ssh_container() {
    if systemctl is-active --quiet natp-sshd-container.service; then
        echo "Reloading natp-sshd-container"
        systemctl reload natp-sshd-container.service;
    fi
}


reload_nginx() {
    if systemctl is-active --quiet nginx.service; then
        echo "Reloading nginx"
        systemctl reload nginx.service
    fi
}


reload_fireball_server() {
    for server in ark-fireball-server ark-fireball-server-special; do
        if systemctl is-active --quiet $server.service; then
            echo "Reloading $server"
            systemctl reload $server.service
        fi
    done
}


reload_fireball_activity() {
    # TODO the fireball packages could add this snippet to a config.d directory
    # that gets run whenever the certificates get refreshed. Would be a nicer
    # way to manage all these helper scripts
    for activity in ark-activity-fireball ark-activity-fireball-dev; do
        if systemctl is-active --quiet $activity.service; then
            echo "Reloading $activity"
            systemctl reload $activity.service
        fi
    done
}



if [ $# -ne 1 ]; then
    usage
    exit 2
fi

echo "Reloading processes for $1"

case "$1" in
    ca.ark.caida.org)
        reload_nginx
        ;;

    collector.ark.caida.org)
        reload_kafka "ark2" "$1"
        ;;

    sirocco.ark.caida.org)
        reload_natp_ssh_container "$1"
        ;;

    spoofer-collector.ark.caida.org)
        reload_kafka "spoofer" "$1"
        ;;

    targets.ark.caida.org)
        reload_nginx
        ;;

    fireball-dev.caida.org|fireball.caida.org|odin.caida.org)
        reload_fireball_server
        ;;

    *)
        reload_fireball_activity
        # TODO should ssh cert renewal happen in this script?
        ;;
esac
