#!/bin/sh

# union-type=overlay needs Linux 4.x and schroot >= 1.6.10-2~.

# ./schroot-config.sh | sudo tee /etc/schroot/chroot.d/sbuild.conf

set -eu

# seed PG_SUPPORTED_DISTS if pgapt.conf is not yet installed
PG_SUPPORTED_DISTS="sid"

# read pgapt config
for dir in . .. $HOME/apt.postgresql.org; do
  test -f $dir/pgapt.conf || continue
  . $dir/pgapt.conf
  break
done

arch="$(dpkg --print-architecture)"

for dist in $PG_SUPPORTED_DISTS; do
		# if arguments are given, execute as command in environment
		# ./schroot-config.sh ./sbuild-update.sh
		if [ "$*" ]; then
			echo "### distribution=$dist architecture=$arch ###"
			export distribution=$dist architecture=$arch
			"$@"
			continue
		fi

		body="$(cat <<-EOF
			type=directory
			groups=sbuild
			root-groups=sbuild
			source-groups=sbuild
			source-root-groups=sbuild
			directory=/home/chroot/$dist-$arch
			union-type=overlay
			union-overlay-directory=/var/run
			
			EOF
		)"

		echo "[$dist-$arch]"
		aliases="$dist-pgdg-$arch,$dist"
		[ $dist = sid ] && aliases="$aliases,default"
		echo "aliases=$aliases"
		echo "$body"
		echo

		echo "[$dist-$arch-sbuild]"
		aliases="$dist-pgdg-$arch-sbuild"
		[ $dist = sid ] && aliases="$aliases,unstable-$arch-sbuild,experimental-$arch-sbuild"
		echo "aliases=$aliases"
		echo "profile=sbuild"
		echo "$body"
		echo
done
