#!/bin/busybox sh
#
# bulk.sh -- basic bulk build script
#
# Copyright (c) 2019 David Demelier <markand@malikania.fr>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

for applet in $(busybox --list); do
	alias $applet="busybox $applet"
done

TOP=$(realpath $(dirname $0)/../)
PROGNAME=$(basename $0)
TMPDIR=/tmp/vanilla-bulk

# Options.
force=0
missing=0

#
# clean
#
# Remove temporary files.
#
clean()
{
	rm -f $TMPDIR/list
}

#
# build
#
# Build a package if not installed unless `force' (-f) has been given. Then
# force its reinstallation.
#
build()
{(
	local name=$(basename $1)

	# TODO: dependencies here.
	echo -n "building $name: "

	if [ $force -eq 1 ] || ! vpk info $name > /dev/null 2>&1; then

		cd $TOP/$pkg

		if vpk build > $TMPDIR/fail.$name 2>&1; then
			echo "ok"
			vpk add -qr /tmp/vpk/$name*pkg.txz
		else
			echo "failed"
			return 1
		fi
	else
		echo "not needed"
	fi
)}

#
# build_missing
#
# Rebuild a package that is installed but not available in /tmp/vpk.
#
build_missing()
{
	local name=$(basename $1)
	local rebuild=0

	# Build if not installed at all.
	if ! vpk info $name > /dev/null 2>&1; then
		rebuild=1
	else
		local version=$(vpk info -m version $name 2> /dev/null)
		local revision=$(vpk info -m revision $name 2> /dev/null)
		local filename="$name#$version-$revision-pkg.txz"

		if [ ! -f /tmp/vpk/$filename ]; then
			rebuild=1
		fi
	fi

	if [ $rebuild -eq 1 ]; then
		build $1
	fi
}

usage()
{
	echo "usage: bulk.sh [-fm] [packages...]"
	exit 1
}

while getopts "fm" arg; do
	case $arg in
	f)
		force=1
		;;
	m)
		missing=1
		force=1
		;;
	*)
		usage
		;;
	esac
done

shift $((OPTIND - 1))

trap "clean; exit 1" INT QUIT TERM
rm -rf $TMPDIR
mkdir -p $TMPDIR

$TOP/Scripts/list.sh > $TMPDIR/list

if [ ! -s $TMPDIR/list ]; then
	echo "abort: no packages to build" 1>&2
	exit 1
fi

total=$(wc -l $TMPDIR/list | awk '{ print $1 }')
current=1

cat $TMPDIR/list | while read -r pkg; do
	echo -n "($current/$total) "

	if [ $missing -eq 1 ]; then
		build_missing $pkg
	else
		build $pkg
	fi

	current=$((current + 1))
done

clean
