#!/usr/bin/env bash

export PATH=$HOME/bin:$PATH

. lib.bash || exit

set -u

usage() {
	echo "Usage: $0 [-f]"
	echo
	echo_opt "-f"		"proceed if username does not match"
}

opt_force=0
opt_addr='grawity@nullroute.lt'

while getopts :f OPT; do
	case $OPT in
	f) opt_force=1;;
	*) lib:die_getopts;;
	esac
done; shift $[OPTIND-1]

if [ "$USER" != grawity ] && (( !opt_force )); then
	vdie "username mismatch"
fi

for cmd in git gpg; do
	if ! have $cmd; then
		vdie "$cmd not found"
	fi
done

if [ ! -d ~/.dotfiles ]; then
	vmsg "downloading ~/.dotfiles"
	git clone "https://github.com/grawity/dotfiles" ~/.dotfiles
	~/.dotfiles/install
fi

if [ ! -s ~/.ssh/authorized_keys ]; then
	sshkeyupdate -r
fi

if ! have crontab; then
	vmsg "skipping cron job (crontab not found)"
elif crontab -l |& grep -q /dist/pull; then
	vmsg "cron job already present"
else
	vmsg "adding cron job"
	(crontab -l; echo "@daily	~/bin/dist/pull") | crontab -
fi

if ! mta=$(PATH=/usr/lib:/usr/sbin:/usr/bin:/bin command -v sendmail); then
	vmsg "skipping ~/.forward (sendmail not found)"
elif [ -s ~/.forward ]; then
	vmsg "~/.forward already present"
else
	vmsg "creating ~/.forward"
	echo "\"|$mta -i $opt_addr\"" > ~/.forward
	vmsg "sending test message"
	$mta -i "$USER" <<-EOF
	Subject: Test from $(hostname)
	Date: $(date "+%a, %d %b %Y %H:%M:%S %z")
	To: <$opt_addr>

	Test mail from $USER ($UID) at $(fqdn || hostname)
	EOF
fi
