+KEY=$3
+PEM=$4
+DOMAIN=$5
+
+# Make sure completed certificate does not already exist
+if test -e "$PEM"; then
+ echo "Error: Refusing to overwrite existing certificate at"
+ echo " $PEM."
+ exit 1
+fi
+
+# Make sure that the key and request do exist
+if test ! -f "$REQUEST"; then
+ echo "Error: The given certificate request file does not exist."
+ exit 1
+fi
+if test ! -f "$KEY"; then
+ echo "Error: The given key file does not exist."
+ exit 1
+fi
+
+# Verify request
+STATUS=$(openssl req -noout -in "$REQUEST" -verify 2>&1)
+if test "$STATUS" != "verify OK"; then
+ echo "Error: This is not a valid certificate request."
+ exit 1
+fi
+if test -n "$DOMAIN"; then
+ CN=$(openssl req -text -in "$REQUEST" | grep "Subject:" | grep "CN=." | \
+ sed -r -e 's/^.*CN=([^/=,]+).*$/\1/1')
+ if test "${CN%%${DOMAIN}}" = "${CN}"; then
+ echo "Error: Domain in cert does not match $DOMAIN."
+ exit 1
+ fi
+fi
+
+# Get new serial number