#!/bin/sh

ETLOG=/var/log/emptytree.log
PORTAGE_TMPDIR=/var/tmp

[ -e /etc/portage/bashrc ] && . /etc/portage/bashrc

log () {
	echo `date`:$* >> $ETLOG
}

report_time () {
    endtime=`cat /proc/uptime |cut -d" " -f1 |cut -d. -f1`
    starttime=$1

    time=`expr $endtime - $starttime`
    hours=`expr $time / 3600`
    left=`expr $time - 3600 \* $hours`
    minutes=`expr $left / 60`
    seconds=`expr $left - 60 \* $minutes`

    log `printf "END:Completed in %sh %02d:%02d" $hours $minutes $seconds`
}

kill_children () {
    local children=`ps h -o pid --ppid $1`
    local child
    for child in $children; do
        kill_children $child
    done
    #ps h $1 2> /dev/null
    kill $1 2> /dev/null
}

starttime=`cat /proc/uptime |cut -d" " -f1 |cut -d. -f1`

if [ "$1" == "kill" ] ; then
    pid=`fgrep :BEGIN: ${ETLOG} |cut -d: -f5`
    if ! grep -q emptytree /proc/$pid/cmdline 2>/dev/null ; then
    	pid=`fgrep :RESUME: ${ETLOG} |cut -d: -f5`
	if ! grep -q emptytree /proc/$pid/cmdline 2>/dev/null ; then
            echo "emptytree does not appear to be running." > /dev/stderr
	    exit 1
	fi
    fi

    kill_children $pid
    
    log "KILLED:$pid"
    exit 0
fi
	

if [ "$1" == "resume" ] ; then
	log "RESUME:$$"
	starttime=`fgrep :BEGIN: ${ETLOG} |cut -d: -f6`
	if /usr/bin/emerge --resume; then
		log "Completed"
		exit 0
	fi
else
	[ -n "$CCACHE_DIR" ] && rm -rf "$CCACHE_DIR"/*
	rm -f $ETLOG
	log "BEGIN:$$:$starttime"

	if /usr/bin/emerge --emptytree world ; then
		report_time $starttime
		exit 0
	fi
fi

# something failed, log it
package=$(tail -n 2 /var/log/emerge.log |sed -ne '1p' |sed -e 's/^.* (\(.*\)::.*/\1/')
log "FAILED:${package}"

# continue
while ! /usr/bin/emerge --resume --skipfirst ; do
	package=$(tail -n 2 /var/log/emerge.log |sed -ne '1p' |sed -e 's/^.* (\(.*\)::.*/\1/')
	log "FAILED:${package}"
	rm -rf $PORTAGE_TMPDIR/portage
done

log "END:$$"

# sometimes a package will fail in emptytree yet pass if you emerge it
# individually. Moreover, if a package did fail, we want to trap it's
# error messages
failures=`fgrep ":FAILED:" ${ETLOG} |cut -d: -f5`
log "REMERGE:Attempting to emerge failed packages individually"

rm -rf $PORTAGE_TMPDIR/portage
for failure in ${failures}; do
    log "REMERGE:${failure}:"
    MAKEOPTS="" /usr/bin/emerge --oneshot "=${failure}" 2>> ${ETLOG} && \
        log "REMERGE:${failure}:Completed successfully"
done

report_time $starttime
exit 0
