#!/bin/sh

myname=`basename "$0"`
mypath=`dirname "$0"`

if [ $# -lt 2 ]; then
	echo "usage: $myname <host> <pem_output_file>"
	exit 1
fi

host="$1"
outfile="$2"

if [ -f "$outfile" ]; then
	echo "Output file \"$outfile\" exists!"
	exit 2
fi

raw_output=`timeout 10 openssl s_client -CApath /usr/lib/ssl  -connect ${host}:443 -showcerts </dev/null 2>/dev/null`
if [ "$?" -ne 0 ]; then
	echo "Host not found or port not open"
	exit 3
fi
cert=`echo "$raw_output" | openssl x509`
verify=`echo "$raw_output" | sed -n 's/^ *\(Verify return code:.*\)/\1/p' | grep -v ": 0"`
echo "$raw_output"| openssl x509 -noout -fingerprint
rc=0
if [ "$verify" ]; then
	rc=`echo "$verify" | sed -n 's/.*Verify return code: \([0-9]*\).*/\1/p'`
fi

cert_cn=`echo "$raw_output" | openssl x509 -subject -noout | sed -n 's/.*CN=\([a-zA-Z0-9.-]*\).*/\1/p'`

# Reset the return code to 0 if it's currently 2, 12, or between 18 and 20
[ $rc -eq 2 -o $rc -eq 12 ] || [ $rc -ge 18 -a $rc -le 20 ] && rc=0

if [ "$cert_cn" = "$host" ]; then
	echo "Certificate hostname matches ${host}."
	cat /dev/null > /zvsphere.config
else
	echo "Certificate hostname does not match: $cert_cn"
	echo "vsws.trusthost=" > /zvsphere.config
	[ $rc -eq 0 ] && rc=99
fi

echo "$cert" > "$outfile"

if [ "$rc" = "0" ]; then
	echo "Certificate verification successful!"
else
	## [ "$verify" ] && echo "$verify"
	echo "Certificate verification failed!"
fi
exit $rc
