#!/bin/sh
# vim:ts=4:sw=4:et

if [ $# -ne 2 ]; then
    echo "usage: $0 distname { PRE-INSTALL | POST-INSTALL }" >&2
    exit 1
fi

case $2 in
    PRE-INSTALL)
        : nothing to do here
        ;;
    POST-INSTALL)
        RSAKEYS=%%PREFIX%%/etc/xrdp/rsakeys.ini
        PRIVATEKEY=%%PREFIX%%/etc/xrdp/key.pem
        CERTIFICATE=%%PREFIX%%/etc/xrdp/cert.pem
        # make sure rsakeys and certificates are private
        umask 077
        # generate rsakeys.ini
        [ -e "$RSAKEYS" ] || %%PREFIX%%/bin/xrdp-keygen xrdp "$RSAKEYS".sample && \
        # generate self-signed certificate
        [ -e "$PRIVATEKEY" -a -e "$CERTIFICATE" ] || \
            %%OPENSSLBASE%%/bin/openssl req \
                 -x509 \
                 -newkey rsa:4096 \
                 -keyout "$PRIVATEKEY".sample \
                 -sha256 \
                 -nodes \
                 -out "$CERTIFICATE".sample \
                 -days 365 \
                 -subj "/CN=$(hostname)"

        for f in "$RSAKEYS" "$PRIVATEKEY" "$CERTIFICATE"
        do
            [ -e "${f}" ] || cp -n "${f}.sample" "${f}"
        done
        ;;
    *)
        echo "usage: $0 distname { PRE-INSTALL | POST-INSTALL }" >&2
        exit 1
        ;;
esac

exit 0
