SRC=branches/8.09
CLONE=ref

parse_pspec() {
	local pspec="$1"
	[ -z "$pspec" ] && return 1
	[ "${pspec%%/*}" = "$pspec" ] && return 1
	p_max="${pspec##*/}"
	p_cur="${pspec%%/*}"
	p_max="$(($p_max))"
	p_cur="$(($p_cur - 1))"
	[ "$p_max" -gt 0 ] || return 1
	[ "$p_cur" -lt "$p_max" ] || return 1
	return 0
}

p_max=
p_cur=
while [ -n "$1" -a -z "${1%%-*}" ]; do
	cmd="$1"; shift
	case "$cmd" in
		-p)
			parse_pspec "$1" || {
				"Invalid parallel build option"
				exit
			}
			echo "Starting build thread $(($p_cur + 1)) of $p_max"
			shift
		;;
	esac
done

TARGETS="$*"
[ -z "$TARGETS" ] && TARGETS="adm5120/router_le adm5120/router_be ar71xx ar7 atheros au1000 avr32 brcm-2.4 brcm47xx ifxmips ixp4xx magicbox ppc40x ppc44x rb532 rdc x86"
[ -n "$p_max" ] && {
	NEW_TARGETS=
	c=0
	for target in $TARGETS; do
		[ "$(($c % $p_max))" -eq "$p_cur" ] && NEW_TARGETS="$NEW_TARGETS $target"
		c="$(($c + 1))"
	done
	TARGETS="$NEW_TARGETS"
}
DL="$HOME/dl"

SVN=https://svn.openwrt.org/openwrt

R="|| return 1"
prepare_dir() {
	local target="$1"
	local dir="${target%%/*}"
	[ "$target" != "$dir" ] && mkdir -p "$dir"
	if [ -f "$target/.prepared" ]; then
		rm -f "$target/.config"
		(cd "$target"; svn up)
	else
		rm -rf "$target"
		if [ -z "$CLONE" ]; then
			svn co "$SVN/$SRC" "$target"
		else
			cp -a "$CLONE" "$target"
			(cd "$target"; svn up)
		fi
		touch "$target/.prepared"
	fi
}

prepare_feeds() {
	if [ -e "feeds.conf" ]; then
		cp feeds.conf "$target/"
	fi
	( cd "$target";
		./scripts/feeds update &&
		./scripts/feeds install -a -p packages &&
		./scripts/feeds install -a -p luci
	)
}

prepare_config() {
	local target="$1"
	local subtarget="${target#*/}"
	local targetname="${target%%/*}"
	[ "$targetname" = "$subtarget" ] && subtarget=
	cat > "$target/.config" <<EOF
CONFIG_ALL=y
CONFIG_TARGET_${targetname}=y
CONFIG_TARGET_${targetname}_${subtarget}=y
CONFIG_TARGET_BOARD="$targetname"
# CONFIG_PACKAGE_ebtables is not set
# CONFIG_PACKAGE_ebtables-utils is not set
# CONFIG_PACKAGE_kmod-ebtables is not set
# CONFIG_PACKAGE_enlightenment is not set
# CONFIG_PACKAGE_etk is not set
# CONFIG_PACKAGE_python-etk is not set
CONFIG_PACKAGE_luci-admin-full=y
CONFIG_PACKAGE_luci-admin-mini=y
EOF
	make -C "$target" defconfig
}

build_target() {
	local target="$1"
	prepare_dir "$target" $R
	prepare_feeds "$target" $R
	prepare_config "$target" $R
	if [ -n "$DL" ]; then
		ln -s "$DL" "$target/dl"
	fi
	make -C "$target" package/base-files/clean
	rm -f "$target/bin/*" 2>/dev/null >/dev/null
	make -C "$target" IGNORE_ERRORS=m FORCE=1
}

log_target() {
	local name="$1"
	if [ "${name%%/*}" != "$name" ]; then
		name="${name%%/*}:${name##*/}"
	fi
	local _c=""
	while [ -f "logs/build-$name.log${_c:+.$_c}" ]; do
		_c=$(( ${_c:-0} + 1))
	done
	tee "logs/build-$name.log${_c:+.$_c}"
}

mkdir -p logs
for target in $TARGETS; do
	( build_target "$target" 2>&1 || exit 1 ) | log_target "$target"
done
