#!/bin/bash

set -eu

. debian/tests/testlib.sh

my_hostname=localhost

OUTFILE="$AUTOPKGTEST_TMP/combined.pem"
CERTFILE="$OUTFILE"
KEYFILE="$OUTFILE"
DEBIAN_FRONTEND=noninteractive make-ssl-cert /usr/share/ssl-cert/ssleay.cnf "$OUTFILE"

echo "check combined key+cert"
check_perms "$OUTFILE" "regular file:root:root:600"
verify_selfsigned
assert_hostname "$my_hostname"
assert_san "DNS:$my_hostname"

CERTFILE="$AUTOPKGTEST_TMP/dummy.crt"
KEYFILE="$AUTOPKGTEST_TMP/dummy.key"
DEBIAN_FRONTEND=noninteractive make-ssl-cert /usr/share/ssl-cert/ssleay.cnf "$KEYFILE" "$CERTFILE"

echo "check split key+cert"
check_perms "$KEYFILE" "regular file:root:root:600"
check_perms "$CERTFILE" "regular file:root:root:644"
verify_selfsigned
assert_hostname "$my_hostname"
assert_san "DNS:$my_hostname"

echo "check hostname override"
rm -f "$KEYFILE" "$CERTFILE"
DEBIAN_FRONTEND=noninteractive make-ssl-cert \
	--hostname example.internal \
	/usr/share/ssl-cert/ssleay.cnf "$KEYFILE" "$CERTFILE"
verify_selfsigned
assert_hostname "example.internal"
assert_san "DNS:example.internal"

echo "check hostname+subjectaltname override"
rm -f "$KEYFILE" "$CERTFILE"
DEBIAN_FRONTEND=noninteractive make-ssl-cert \
	--hostname example.internal \
	--subjectaltname DNS:example2.internal \
	/usr/share/ssl-cert/ssleay.cnf "$KEYFILE" "$CERTFILE"
verify_selfsigned
assert_hostname "example.internal"
assert_san "DNS:example.internal,DNS:example2.internal"

echo "check subjectaltname override"
rm -f "$KEYFILE" "$CERTFILE"
DEBIAN_FRONTEND=noninteractive make-ssl-cert \
	--subjectaltname DNS:example2.internal \
	/usr/share/ssl-cert/ssleay.cnf "$KEYFILE" "$CERTFILE"
verify_selfsigned
assert_hostname "$my_hostname"
assert_san "DNS:$my_hostname,DNS:example2.internal"

exit $RC
