# vim: ft=zsh noet
typeset -g FSB_EMERGE_JOBS
: ${FSB_EMERGE_JOBS:=$(cat /proc/cpuinfo | grep '^processor' | wc -l)}

local emerge_ret emerge_calls current_failure previous_failure failure resolution
local -a emerge_cmd chroot_cmd last_emerge_status

if [[ -o xtrace ]]; then
	chroot_cmd=( zsh -x $build_dir/chroot.sh /bin/bash --login -x )
else
	chroot_cmd=( $build_dir/chroot.sh /bin/bash --login )
fi

emerge_cmd=( FEATURES=-userpriv emerge --jobs $FSB_EMERGE_JOBS --verbose-conflicts )

emerge_calls=1
previous_failure=""
fsb_chroot_bash_nocheck $emerge_cmd "$@"
emerge_ret=$?

while (($emerge_ret)); do
	last_emerge_status=( ${(f)"$(emerge_log_sanitizer.sed <$build_dir/var/log/emerge.log | last_emerge.awk)"} )
	current_failure=$(printf "%s\n" $last_emerge_status[2,-1] | cut -f 2 | sort)
	if [[ $previous_failure == $current_failure ]]; then
		die "Hackfix: Stuck on repeating error"
	fi

	for failure in $last_emerge_status[2,-1]; do
		resolution=$(portage_logcat $=failure $build_dir | awk -v EMERGE_CMD="$emerge_cmd" '
/configure: error: XML::Parser perl module is required/ {
	print EMERGE_CMD " -1 XML-Parser"
	exit 0
}
		')
		if [[ -n $resolution ]]; then
			break
		fi
	done

	if [[ -z $resolution ]]; then
		die "Emerge failed and no autoresolution: $*"
	fi

	$chroot_cmd -c "$resolution" || die "Hackfix autoresolution failed: $resolution"

	emerge_calls=$[ $emerge_cmd + 1 ]
	fsb_chroot_bash_nocheck $emerge_cmd "$@"
	emerge_ret=$?
done
return $emerge_ret