#!/bin/bash

# test snakeoil certificate (key pair) generated by the systemd service
# on start, systemd service checks if the snakeoil key exists, if not, it
# generates a new one.

set -eu

. debian/tests/testlib.sh

KEY_SIZE=3072
SNAKEOIL_CERT="/etc/ssl/certs/ssl-cert-snakeoil.pem"
SNAKEOIL_KEY="/etc/ssl/private/ssl-cert-snakeoil.key"

assert_keypair_match() {
	local cert_mod key_mod
	cert_mod=$(openssl x509 -noout -modulus -in "$SNAKEOIL_CERT")
	key_mod=$(openssl rsa -noout -modulus -in "$SNAKEOIL_KEY")
	expect "$cert_mod" "$key_mod" "key does not match certificate"
}

restart_service() {
    systemctl restart ssl-cert.service
}

rm_cert_and_key() {
    rm -f "$SNAKEOIL_CERT" "$SNAKEOIL_KEY"
}

check_cert_and_key() {
    if [ ! -f "$SNAKEOIL_CERT" ] || [ ! -f "$SNAKEOIL_KEY" ]; then
        echo "Cert or key file is missing"
        exit 1
    fi
}

rm_cert_and_key
restart_service
check_cert_and_key

assert_keypair_match
