#!/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.
#

alias basename="busybox basename"
alias dirname="busybox dirname"
alias echo="busybox echo"
alias find="busybox find"
alias grep="busybox grep"
alias realpath="busybox realpath"

TOP=$(realpath $(dirname $0)/../)
PROGNAME=$(basename $0)

rm -f /tmp/fail.*

force=0
missing=0

#
# build
#
# Build a package if not already installed.
#
build()
{(
	name=$(basename $1)

	if [ $force -eq 1 ] || ! vpk info $name > /dev/null 2>&1; then
		# TODO: dependencies here.
		echo -n "building $name: "

		cd $TOP/$pkg

		if vpk build > /tmp/fail.$name 2>&1; then
			rm -f /var/lib/vpk/$name
			rm -f /tmp/fail.$name
			echo "ok"
			yes | vpk install -t none /tmp/vpk/$name*pkg.txz
		else
			echo "failed"
			return 1
		fi
	fi
)}

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

	# Build if not installed at all.
	if ! vpk info $name > /dev/null 2>&1; then
		rebuild=1
	else
		version=$(vpk info -m version $name 2> /dev/null)
		revision=$(vpk info -m revision $name 2> /dev/null)
		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))

$TOP/Scripts/list.sh "$@" | while read -r pkg; do
	if [ $missing -eq 1 ]; then
		build_missing $pkg
	else
		build $pkg
	fi
done
