#!/bin/sh

DOMAIN="$1"

if [ -z "$DOMAIN" ]; then
	echo "Usage : "$(basename "$0")" domain" >&2
	echo "  Will check if \$domain.key, \$domain.cer and \$domain.chain.txt are correct" >&2
	exit 1
fi

# Check key and certificate modulus
KEY_MOD=$(openssl rsa  -noout -modulus -in ${DOMAIN}.key | openssl md5)
CER_MOD=$(openssl x509 -noout -modulus -in ${DOMAIN}.cer | openssl md5)

if [ "${KEY_MOD}" != "${CER_MOD}" ]; then
	echo "Error : key does not match certificate" >&2
	exit 2
fi

# Check certificate consistency
openssl verify -CApath /etc/ssl/certs -CAfile ${DOMAIN}.chain.txt ${DOMAIN}.cer | grep -q "^${DOMAIN}.cer: OK$"
if [ $? -ne 0 ]; then
	openssl verify -CApath /etc/ssl/certs -CAfile ${DOMAIN}.chain.txt ${DOMAIN}.cer >&2
	echo "Error while verifying certificate chain" >&2
	exit 3
fi

echo "Success"
exit 0

