#!/bin/sh -e
#
#    bootmail - email some people when this system (re)boots
#
#    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/>.

# Get GPG_OPTS
. /etc/bootmail/gpg.conf
PKG=bootmail

# 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

print_mail_text() {
	# Print the header
	echo "$subject"
	echo
	# Update the motd now, so that it's ready when we append it
	[ -d /etc/update-motd.d ] && run-parts --lsbsysinit /etc/update-motd.d > /etc/motd
	# Concatenate all specified boot logs
	if [ -f "/etc/bootmail/logs" ]; then
		for i in $(cat /etc/bootmail/logs); do
			echo
			echo "=================="
			echo "[$i]:"
			echo "=================="
			cat "$i"
			echo "=================="
			echo
		done
	fi
	echo "To verify this message, import [$FROM_MAIL]'s GPG key with:"
	KEYID=$(gpg $GPG_OPTS --list-keys $FROM_MAIL | grep -m1 "^pub" | sed -e "s:.*/::" -e "s: .*::")
	echo "gpg --keyserver pgp.mit.edu --recv-keys 0x$KEYID"
	echo
	gpg $GPG_OPTS --fingerprint "$FROM_MAIL" | sed -e "s/\s\+/ /g"
	echo
}


# This should be comma-separated, and can be configured via debconf:
#  sudo dpkg-reconfigure bootmail
recipients=
[ -f /etc/bootmail/recipients ] && recipients="$(cat /etc/bootmail/recipients)"
if [ -z "$recipients" ]; then
	echo "No recipients defined in [/etc/bootmail/recipients]" 1>&2
	exit 0
fi
hostname=$(hostname -f)
date=$(date)
if [ "$1" = "--shutdown" ]; then
	subject="bootmail: [$hostname] shutting down on [$date]"
else
	subject="bootmail: [$hostname] booted on [$date]"
fi
# Must use the sed to ensure the mail renders properly in most readers
logger -t "bootmail" "Sending bootmail to [$recipients]"
print_mail_text | sed -e "s/[^[:print:]]//g" | rootsign | mail -s "$subject" "$recipients" -- -F "Bootmail" -f "$FROM_MAIL"
