#!/bin/bash
WORKDIR=~/development/hasher

export TARGET=`uname -m`
export NPROCS=$((`grep -c ^processor /proc/cpuinfo` * 4))
export WORKDIR=`realpath "$WORKDIR"`

if [ "$TARGET" != "x86_64" ]; then
	TARGET=i586
fi

mount_workdir()
{
	rm -f $WORKDIR/repo 2> /dev/null
	rmdir $WORKDIR/repo 2> /dev/null
	mount $WORKDIR
	ln -s $POCKET $WORKDIR/repo
}

umount_workdir()
{
	# if 'chroot' dir exists, it meant that build was not succesful
	# and if so, we may need to see what happens
	if [ ! -d $WORKDIR/chroot ]; then
		umount $WORKDIR
	fi
}

umount_workdir_force()
{
	umount $WORKDIR > /dev/null 2> /dev/null
}

try_build()
{
	echo "Building for $TARGET"
	POCKET=$1
	SPEC=$2
	TYPE=$3
	if [ -z "$TYPE" ]; then
		TYPE=SS
	fi
	if [ "$POCKET" != "" ]; then
		POCKET=~/development/pockets/"$POCKET"
	else
		POCKET=~/development/repo
	fi
	export POCKET
	mkdir -p "$POCKET"

	umount_workdir_force
	mount_workdir

	export NPROCS=`nprocs 4`

	cmd=""
	if [ "$TARGET" == "i586" ]; then
		cmd=i586
	fi

	APTCONF=/etc/apt/apt.conf.$TYPE.$TARGET

	if [ ! -f "$APTCONF" ]; then
		echo $APTCONF not found > /dev/stderr
		exit -1
	fi

	echo ">>> Building for target $TARGET"
	if [ -z "$SPEC"  ]; then
		$cmd gear-hsh-build \
			--target=$TARGET \
			--prefix "$WORKDIR" \
			--repo repo \
			-- \
			./.git \
			-- \
			--excludedocs \
			--install-langs=en,ru \
			--repackage-source \
			--nprocs="$NPROCS" \
			--target=$TARGET \
			--apt-conf $APTCONF \
			--build-args='--with debug --enable debug'
	else
		$cmd hsh \
			--target=$TARGET \
			--excludedocs \
			--install-langs=en,ru \
			--repackage-source \
			--nprocs="$NPROCS" \
			--build-args='--with debug --enable debug' \
			--apt-conf "$APTCONF" \
			"$WORKDIR" \
			"$SPEC"
	fi

	umount_workdir
}

try_build_targets() {
	try_build "$1" "$2" "$3"

	if [ "$TARGET" == "x86_64" ]; then
		export TARGET=i586
		try_build "$1" "$2" "$3"
	fi
}

# ? not worked ?	
#	--build='--define \"_unpackaged_files_terminate_build 1\"' \
