#!/bin/sh

set -e

BUILDDIR="${BUILDDIR:-/tmp/buildd}"

# exit if we are in the same UTS namespace as init ( != 2nd build )
[ "$(readlink /proc/1/ns/uts)" = "$(readlink /proc/self/ns/uts)" ] && exit 0

#
# doing variations for the 2nd builds:
#
REAL_HOSTNAME=$(hostname)
echo "disorder-fs debug: Running on $REAL_HOSTNAME."

echo "I: Changing host+domainname to test build reproducibility" >&2
sed -e '/^127.0.0.1/s/$/ i-capture-the-hostname i-capture-the-hostname.i-capture-the-domain/' -i /etc/hosts
hostname i-capture-the-hostname
domainname i-capture-the-domain
echo "I: Adding a custom variable just for the fun of it..." >&2
export CAPTURE_ENVIRONMENT="I capture the environment"

echo "I: Changing /bin/sh to bash" >&2
echo "dash dash/sh boolean false" | debconf-set-selections
DEBIAN_FRONTEND=noninteractive dpkg-reconfigure dash
if [ -n "$BUILDUSERNAME" ] ; then
	echo "I: Setting $BUILDUSERNAME's login shell to /bin/bash" >&2
	usermod -s /bin/bash $BUILDUSERNAME
	if [ -n "$BUILDUSERGECOS" ] ; then
		echo "I: Setting $BUILDUSERNAME's GECOS to $BUILDUSERGECOS" >&2
		usermod -c "$BUILDUSERGECOS" $BUILDUSERNAME
	fi
fi

# disable disorderfs due to #844498
#exit 0
# use disorderfs on armhf only for now
if [ "$(dpkg --print-architecture)" != "armhf" ] ; then
	exit 0
elif [ "$REAL_HOSTNAME" != "bpi0" ] ; then
	exit 0
else
	echo "disorder-fs debug: bpi0, yay, enabling disorderfs now…"
fi

# use disorderfs
if [ -x /usr/bin/disorderfs ] ; then
	echo -n "Moving $BUILDDIR to /tmp/disorderfs and mounting this as $BUILDDIR via the fuse disorderfs…"
	mknod -m 666 /dev/fuse c 10 229
	mv "$BUILDDIR" /tmp/disorderfs
	mkdir "$BUILDDIR"
	disorderfs --multi-user=yes /tmp/disorderfs "$BUILDDIR"
	echo " done."
else
	echo "Warning: disorderfs not available."
fi