#!/bin/sh

set -e

PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/local/sbin:/usr/local/bin

eval `puppet config print \
	codedir default_manifest lastrunreport rundir | tr -d ' '`

apply_lock=$rundir/.overnet_apply_lock
sitepp=$codedir/$default_manifest/site.pp

platform=`uname -s`
if [ "$platform" = "Linux" ]; then
	distro=`lsb_release -si`
fi

fatal() {
	echo "$(basename $0): $1" >&2
	exit 1
}

update_manifests() {
	if [ "$platform" = "Linux" -a "distro" = "Debian" ]; then
		DEBIAN_FRONTEND=noninteractive
		apt-get update
		apt-get install -qy overnet-puppet-manifests
	else
		fatal "current Puppet manifests broken; update manually"
	fi
}

flock() {
	perl -MFcntl=:flock -e \
		'$lk=shift; open(LK,">",$lk) || die($!); \
		flock(LK,LOCK_EX|LOCK_NB) || exit(0); \
		system(join(" ",@ARGV));' $@
}

run_puppet() {
	noop="$1"
	# The "flock" shell util does not exist on all platforms.
	# We discard flock() errors since it should mean another instance
	# is running.
	if tty -s; then
		flock $apply_lock puppet apply $sitepp --test $noop
	else
		flock puppet apply $sitepp $noop >/dev/null
	fi
	st=$?
	if [ $st -eq 1 ]; then
		# With detailed exit codes, status 1 means the run
		# failed entirely. We should make sure we get new
		# manifests.
		update_manifests
		exit 1
	fi
	return $st
}

usage() {
	echo "Usage: $(basename $0) [-h] [-f] [-t <interval in minutes>]"
	echo "       -h              Help"
	echo "       -f              Force run, disregarding the minimum interval"
	echo "       -n              Pass --noop to puppet"
	echo "       -t <interval>   Wait this many minutes before next run"
	echo "       -s <path>       Path to site.pp"
}

args=`getopt fnht:s: $*`
if [ $? -ne 0 ]; then
	usage
	exit 2
fi

set -- $args
force="false"
noop=""
interval=60
while [ $# -ne 0 ]; do
	case "$1" in
		-f)
			force="true"
			shift
			;;
		-h)
			usage
			exit 0
			;;
		-n)
			noop="--noop"
			shift
			;;
		-t)
			interval="$2"
			shift
			shift
			;;
		-s)
			sitepp="$2"
			shift
			shift
			;;
		--)
			shift
			break
			;;
	esac
done

[ `whoami` = root ] || fatal "must be run as root"

st=0

if [ "$force" = "true" -o ! -f "$lastrunreport" \
    -o -z "$(find $lastrunreport -mmin -${interval})" ]; then
	run_puppet "$noop"
	st=$?
fi

exit $st
