#!/bin/sh -e
#
#    rootsign - sign stdin with the local root user's private/public keypair
#               and display on stdout; suitable for piping to mail
#
#    Copyright (C) 2011 Dustin Kirkland <kirkland@ubuntu.com>
#
#    Authors:
#        Dustin Kirkland <kirkland@ubuntu.com>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Ensure root
if [ "$(id -u)" != "0" ]; then
	echo "Only root can run this program" 1>&2
	exit 13
fi

PKG=rootsign
# All sorts of things go wrong if you don't own your $HOME dir.
# This happens under sudo, if you don't use the -H option.
if [ ! -O "$HOME" ]; then
        echo "Cannot run $PKG because [$USER] does not own [$HOME]" 1>&2
        if [ -n "$SUDO_USER" ]; then
                echo "To run $PKG under sudo, you MUST use 'sudo -H'" 1>&2
        fi
        exit 1
fi

# Get GPG_OPTS and FROM_MAIL
. /etc/bootmail/gpg.conf

[ -n "$KEYSERVER" ] || KEYSERVER="pgp.mit.edu"

# Create a GPG key for message signing, if necessary
if ! gpg $GPG_OPTS --list-keys "$FROM_MAIL" >/dev/null 2>&1; then
	# Otherwise, generate a new one from scratch
	# Use openssl rather than gpg to generate a key, as openssl doesn't block on lack of entropy.
	# Perhaps slightly less secure than gpg, but all we're doing is signing some simple emails.
	openssl genrsa 4096 2>/dev/null | PEM2OPENPGP_USAGE_FLAGS=certify,sign pem2openpgp "$FROM_MAIL" | gpg $GPG_OPTS --import >/dev/null 2>&1
	# Save a copy of the public key, for recipients to gpg --import
	mkdir -m 755 -p /var/lib/rootsign
	gpg $GPG_OPTS --export -a "$FROM_MAIL" >/var/lib/rootsign/rsa.pub 2>/dev/null
	# Background a push of the key to a keyserver
	gpg $GPG_OPTS --keyserver "$KEYSERVER" --send-keys "$FROM_MAIL" &
	chmod 644 /var/lib/rootsign/rsa.pub
fi

CLEARSIGN="--clearsign"
opts="$GPG_OPTS"
if [ -s /etc/bootmail/gpgkeys ]; then
	opts="$opts -e"
	for i in $(cat /etc/bootmail/gpgkeys | sed "s/,/ /g"); do
		if gpg $GPG_OPTS --list-keys "$i" >/dev/null 2>&1; then
			opts="$opts -r $i"
			CLEARSIGN=
		else
			if gpg $GPG_OPTS --recv-keys $i; then
				opts="$opts -r $i"
				CLEARSIGN=
			else
				echo "ERROR: You need to manually import the key [$i] with:" 1>&2
				echo "  cat public_key | gpg $GPG_OPTS --import" 1>&2
				exit 1
			fi
		fi
	done
fi

# Sign stdin
cat /dev/stdin | gpg $opts -a -s $CLEARSIGN
