#!/bin/sh

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

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

body="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=/home/chroot/overlay
"

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

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 "setup.fstab=sbuild/fstab.$dist"
echo "$body"

cat > /etc/schroot/sbuild/fstab.$dist <<EOF
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
/proc           /proc           none    rw,bind         0       0
/sys            /sys            none    rw,bind         0       0
/dev/pts        /dev/pts        none    rw,bind         0       0
tmpfs           /dev/shm        tmpfs   defaults        0       0
# Mount buildd home so ~/.m2 is available
/home/buildd    /home/buildd    tmpfs   defaults,mode=1777,size=500M  0       0
# Bind-mount a host directory to /build so we don't build on the root overlayfs
/home/chroot/build  /build   none    rw,bind         0       0
# Some packages cache some build artifacts in /var/tmp
/var/tmp	/var/tmp	none	rw,bind		0	0
# Cache .deb files between builds
/home/chroot/archives/$dist /var/cache/apt/archives  none  rw,bind  0  0
EOF

mkdir -p /home/chroot/archives/$dist

done > /etc/schroot/chroot.d/sbuild.conf
