#!/bin/sh

set -e

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

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"
	extra_modules="$2"
	modules='$basemodulepath'
	if [ ! -z "$extra_modules" ]; then
		modules="$extra_modules:$modules"
	fi
	# 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 \
			--modulepath="'$modules'" $noop
	else
		flock puppet apply $sitepp --modulepath="'$modules'" \
			$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"
	echo "       -m <modules>    Colon-separate extra module paths"
}

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

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

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

if [ ! -r /var/cache/overnet-puppet-apply ]; then
	puppet config print \
		codedir default_manifest lastrunreport rundir | \
		tr -d ' ' > /var/cache/overnet-puppet-apply
fi

. /var/cache/overnet-puppet-apply

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

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


st=0

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

exit $st
