#! /bin/bash

APACHE_USER=${1:-www-data}
KEYLENGTH=${2:-4096}
SAFECHAT_NAME=${3:-Safe Chat}
SAFECHAT_COMMENT=${4:-https://safechat.ch}
SAFECHAT_EMAIL=${5:-server@safechat.ch}
PASSWORD=${PASSWORD:-${6:-$(pwgen 80 1)}}

if sudo -u ${APACHE_USER} gpg2 -K "${SAFECHAT_NAME}"; then
    FINGERPRINT=$(LANG= sudo -u ${APACHE_USER} gpg2 --fingerprint "${SAFECHAT_NAME}" \
                  | sed -n 's, ,,g;s,.*Keyfingerprint=,,p')
    echo "deleting key ${SAFECHAT_NAME} with fingerprint ${FINGERPRINT}"
    sudo -u ${APACHE_USER} gpg2 --batch --delete-secret-and-public-key "${FINGERPRINT}"
fi
if sudo -u ${APACHE_USER} gpg2 -K "${SAFECHAT_NAME}"; then
    echo "**** error: key exists and cannot be deleted" 1>&2
    exit 1
fi

sudo -u ${APACHE_USER} gpg -v -v --gen-key --batch <<EOF
Key-Type: RSA
Key-Length: ${KEYLENGTH}
Subkey-Type: RSA
Subkey-Length: ${KEYLENGTH}
Name-Real: ${SAFECHAT_NAME}
Name-Comment: ${SAFECHAT_COMMENT}
Name-Email: ${SAFECHAT_EMAIL}
Expire-Date: 0
Passphrase: ${PASSWORD}
%echo generating key for ${SAFECHAT_NAME} ...
%commit
%echo done.
EOF
