#!/bin/bash
PKG=$1
MASK=`cl-core --method core_variables_show --only-value install.os_nvidia_mask 2>/dev/null`
WORLD=/var/lib/portage/world
LOG=/var/log/calculate/video-install.log
:> $LOG
WRITEPKG=
[[ -z "$(tail -c1 $WORLD)" ]] || echo >> $WORLD

while read category pn pv package_dir pkgname pkgmask;
do
	if [[ $PKG == $pkgname ]] && [[ $MASK == $pkgmask ]]
	then
		if [[ $package_dir == "binary" ]]
		then
			ACCEPT_KEYWORDS="**" FEATURES="-getbinpkg" PKGDIR=/usr/portage/packages emerge -OK1 =$category/$pn-$pv &>>$LOG || exit 1
		else
			cd $package_dir
			ebuild=$category/$pn/$pn-${pv}.ebuild
			[[ -f $ebuild ]] || git checkout $(dirname $ebuild) >>$LOG
			DISTDIR=/usr/portage/distfiles ebuild $ebuild merge --skip-manifest &>>$LOG || exit 1
			WRITEPKG="$category/$pn"
		fi
	fi
done </var/cache/calculate/video_drivers

[[ -n $WRITEPKG ]] && echo $WRITEPKG >>$WORLD
