#! /usr/bin/env bash

set -eo pipefail

CSR_TMP="$(mktemp)"

cat >"$CSR_TMP"

AWK_GET_CN='/^subject=CN = / { gsub(/^subject=CN = /, ""); print }'
CERT_CN="$( (openssl x509 -noout -subject -req -in "$CSR_TMP" 2>&1 || true) | awk "$AWK_GET_CN")"

cd ~/
(
	# easyrsa does prevent importing a cert to a file that already exists,
	# but the message isn't great (it asks you to choose a different file
	# name, and we don't provide a way to have a file name different from
	# the CN, you need to change the CN instead).
	if [ -e "pki/reqs/$CERT_CN.req" ]; then
		echo "Common name already in use: $CERT_CN" >&2
		echo  >&2
		echo "You must choose a different common name that has not been used by a previous certificate." >&2
		echo "Delete your certificate request, then choose a different common name and try again." >&2
		exit 1
	fi
	/usr/share/easy-rsa/easyrsa import-req "$CSR_TMP" "$CERT_CN"
	echo yes | /usr/share/easy-rsa/easyrsa sign-req client "$CERT_CN"
) >/dev/null

cat "pki/issued/$CERT_CN.crt"
