#! /bin/bash
# script for creating fingerprints according to https://bugs.cacert.org/view.php?id=1254

TMP=/tmp/1254-$$
trap "rm -rf ${TMP}" 0 1 2 3 15

CLASS1=/home/cacert/www/www/certs/root.crt
test -f ${CLASS1} || CLASS1=/etc/ssl/CA/cacert.crt
CLASS3=/home/cacert/www/www/certs/class3.crt
test -f ${CLASS3} || CLASS3=/etc/ssl/class3/cacert.crt
SIGNER_HOME=/home/signer/www/CommModule
test -d ${SIGNER_HOME} || SIGNER_HOME=/root/CommModule

mkdir -m 0700 ${TMP}
cd ${TMP}
cp -p ${CLASS1} class1.crt
cp -p ${CLASS3} class3.crt
cp -p ${SIGNER_HOME}/secring0.gpg secring.gpg
cp -p ${SIGNER_HOME}/pubring0.gpg pubring.gpg

ls -l
echo "Type ENTER to continue"
read line

wrap_none()
{
	cat
}

wrap_simple()
{
	sed -e 's/=/=\
  /'
}

wrap_complex()
{
	awk -F'=' '
NF == 2 {
	    print $1
	    len = length($2)
	    if (len < 83) {
		print "  " $2
	    } else if ((len + 1) % 14 == 0) {
		for (base = 1; base < len; base += 3 * 14) {
		    print "  " substr($2, base, 3 * 14 - 1)
		}
	    } else if ((len + 1) % 16 == 0) {
		for (base = 1; base < len; base += 3 * 16) {
		    print "  " substr($2, base, 3 * 16 - 1)
		}
	    } else {
		print "  " $2
	    }
	}
NF != 2 {
	    print
	}
'
}

clearsign()
{
	FPR=$1
	WRAP=$2
	shift; shift
	ALGLIST="$*"

	rm -f ${FPR}.asc
	(
	echo "Fingerprints for the CAcert Class 1 Root certificate:"
	echo "====================================================="
	echo
	echo "for a in ${ALGLIST}; do \\"
	echo "openssl x509 -noout -fingerprint -\$a -in class1.pem ; done"
	echo
	for hash in ${ALGLIST}
	do
		openssl x509 -noout -fingerprint -$hash -in class1.crt | ${WRAP}
	done
	echo
	echo "Fingerprints for the CAcert Class 3 Intermediate certificate:"
	echo "============================================================="
	echo
	echo "for a in ${ALGLIST}; do \\"
	echo "openssl x509 -noout -fingerprint -\$a -in class3.pem ; done"
	echo
	for hash in ${ALGLIST}
	do
		openssl x509 -noout -fingerprint -$hash -in class3.crt | ${WRAP}
	done
	echo 
	echo "Fingerprints for the CAcert OpenPGP signing key:"
	echo "================================================"
	echo
	echo "LC_ALL=C gpg --list-key --fingerprint gpg@cacert.org" 
	echo
	LC_ALL=C gpg --homedir . --list-key --fingerprint gpg@cacert.org
	) >${FPR}
	gpg --homedir . --clearsign ${FPR}
	rm -f ${FPR}
}

for wraptype in none simple complex
do
	clearsign /tmp/fingerprint-long-${wraptype}.txt wrap_${wraptype} \
		"md4 md5 sha1 ripemd160 sha224 sha256 sha384 sha512"
	clearsign /tmp/fingerprint-short-${wraptype}.txt wrap_${wraptype} \
		"sha1 sha256 sha512"
done

gpg --homedir . --detach-sign --armor class1.crt
gpg --homedir . --detach-sign --armor class3.crt

mv class1.crt.asc /tmp
mv class3.crt.asc /tmp

cd /tmp
rm -rf ${TMP}
tar cfv files-1254.tar *.asc
tar tvf files-1254.tar
ls -l files-1254.tar
