#!/bin/bash
# No way I try to deal with a crippled sh just for POSIX foo.

# Copyright (C) 2009 Joerg Jaspert <joerg@debian.org>
#
# 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; version 2.
#
# 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, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

# exit on errors
set -e
set -o pipefail
# make sure to only use defined variables
set -u
# ERR traps should be inherited from functions too. (And command
# substitutions and subshells and whatnot, but for us the functions is
# the important part here)
set -E

# We sleep a while here, as cron - and as such @reboot jobs like this
# one - are started pretty early during boot. With parts of the system
# still missing, most noticable for us is a not-yet-started postgres...
sleep 75

# import the general variable set.
export SCRIPTVARS=/srv/ftp-master.debian.org/dak/config/debian/vars
. $SCRIPTVARS

# common functions are "outsourced"
. "${configdir}/common"

# usually we are not using debug logs. Set to 1 if you want them.
DEBUG=0

# our name
PROGRAM="dinstall_reboot"

# where do we want mails to go? For example log entries made with error()
if [[ ${HOSTNAME} != fasolo ]]; then
    # Not our ftpmaster host
    MAILTO=${MAILTO:-"root"}
else
    # Yay, ftpmaster
    MAILTO=${MAILTO:-"ftpmaster@debian.org"}
fi

# Marker for dinstall start
DINSTALLSTART="${lockdir}/dinstallstart"
# Marker for dinstall end
DINSTALLEND="${lockdir}/dinstallend"

set +e
starttime=$(/usr/bin/stat -c %Z "${DINSTALLSTART}")
endtime=$(/usr/bin/stat -c %Z "${DINSTALLEND}")
set -e

if [ ${endtime} -gt ${starttime} ]; then
	# Great, last dinstall run did seem to end without trouble, no need to rerun
	log "Last dinstall run did end without trouble, not rerunning"
	exit 0
else
	# Hrm, it looks like we did not successfully end the last run.
	# This either means dinstall did abort due to an error, or we had a reboot
	# No way to tell, so lets restart and see what happens.

	# Make sure we are not fooled by some random touching of the files, only
	# really restart if we have the first stage stampfile there, indicating that
	# dinstall got started
	if [ -f "${stagedir}/savetimestamp" ]; then
		log "Seems we have to restart a dinstall run after reboot"
		${configdir}/cronscript dinstall
	fi
fi
