#!/bin/bash

source /sbin/functions.sh

do_exit () {
	[ -z "${TEMP_DIR}" ] && exit $1
	rm "${TEMP_DIR}/"emerge.log*
	rm -f "${TEMP_DIR}/"*":"*
	rmdir "${TEMP_DIR}"
	exit $1
}

if [ $# != 1 ]
then
	eerror "Expected 1 argument: the place to save the output to. Was given $#"
	do_exit 1
fi

if ! touch "$1"
then
	eerror "Couldn't write to $1"
	do_exit 1
fi

rm -f "$1" &>/dev/null

[ -z "${EMERGE_LOG}" ] && EMERGE_LOG="/var/log/emerge.log"

if [ ! -f "${EMERGE_LOG}" ]
then
	eerror "${EMERGE_LOG} isn't a file"
	do_exit 1
fi

if [ ! -r "${EMERGE_LOG}" ]
then
	eerror "Couldn't read ${EMERGE_LOG}"
	eerror "Run as root, a user in the portage group, or set EMERGE_LOG"
	eerror "environmental variable to a readable portage log"
	do_exit 1	
fi

TEMP_DIR="`mktemp -d`"

if [ $? != 0 ]
then
	eerror "Failed to make a temporary directory"
	do_exit 1
fi

ebegin "Getting merge times from ${EMERGE_LOG}..."

	sed -n '
		s#\([0-9]*\):  \(:::\|>>>\) *\(completed\|\) emerge ([0-9]* of [0-9]*) \([^/]*\)/\([^ ]*\) .*#\1:\3:\4:\5#p
	' "${EMERGE_LOG}" > "${TEMP_DIR}/emerge.log.1"

	if [ $? != 0 ]
	then
		eerror "sed failed"
		do_exit 1
	fi

eend 0

num_todo=`wc -l "${TEMP_DIR}/emerge.log.1" | cut -d' ' -f1`
num_done=0
progress=0

bar="["
for n in `seq 3 ${COLS}`
do
	bar="${bar} "
done
bar="${bar}]"

ebegin "Matching start and completion times..."

	echo -en '\r'"${bar}" >&2

	for line in `tac "${TEMP_DIR}/emerge.log.1"`
	do
		package=`echo ${line} | cut -d':' -f3,4`
		pkgfile="${TEMP_DIR}/${package}"
		my_time="`echo ${line} | cut -d':' -f1`"

		if [ "`echo ${line} | cut -d':' -f2`" = "completed" ]
		then
			echo ${my_time} > "${pkgfile}"
		else
			if [ -f "${pkgfile}" ]
			then
				echo ${package/://} $((`cat "${pkgfile}"`-my_time)) >> "${TEMP_DIR}/emerge.log.2"
				rm -f "${pkgfile}"
			fi
		fi
		
		progress=$((progress+COLS-1))
		num_done=$((num_done+1))

		if [ ${progress} -ge ${num_todo} ]
		then
			bar="${bar/ />}"
			bar="${bar/\>\>/=>}"
			progress=$((progress-num_todo))
			echo -en '\r'"${bar}" $((100*num_done/num_todo))% >&2
		fi

	done

	for i in `ls ${TEMP_DIR}/*:* 2>/dev/null`
	do
		ewarn "${i} but not started! This shouldn't happen!"
	done

eend 0

if ! cp "${TEMP_DIR}/emerge.log.2" "$1"
then
	eerror "The final copy failed for some reason"
	do_exit 1
fi

echo
einfo "The output was saved to $1"

do_exit 0

