#!/bin/bash -e

if test -f /etc/setup-debootstrap.conf; then
    . /etc/setup-debootstrap.conf
fi

archs=${archs:-"i386 amd64"}

distros=${distros:-"xenial wily vivid trusty precise buster stretch jessie wheezy squeeze sid"}
user=${user:-"${USER},jenkins"}

for arch in ${archs}; do
    for distro in ${distros}; do
        if test -e /usr/share/debootstrap/scripts/${distro}; then
            echo "******** update $distro $arch ********" 1>&2
            if ! test -f /etc/schroot/chroot.d/${distro}-${arch}; then
                echo " ----    configure schroot $distro $arch" 1>&2
                sudo bash -c "cat > /etc/schroot/chroot.d/${distro}-${arch}" \
                    <<EOF
[${distro}_${arch}]
description=${distro} ${arch}
directory=/var/chroot/${distro}_${arch}
users=${user}
root-groups=root
root-users=${user}
type=directory
${additional_definitions}
EOF
            fi
            if ! test -d /var/chroot/${distro}_${arch}; then
                echo " ----    install schroot $distro $arch" 1>&2
                sudo debootstrap --arch=$arch $distro \
                    /var/chroot/${distro}_${arch}
            fi
	    if grep -q ubuntu /var/chroot/${distro}_${arch}/etc/apt/sources.list && \
                ! grep -q multiverse /var/chroot/${distro}_${arch}/etc/apt/sources.list; then
	        sudo -u ${user%%,*} schroot -d / \
		    -c ${distro}_${arch} -u root -- \
		    perl -pi -e 's#main.*$#main universe multiverse#g' \
                    /etc/apt/sources.list
            fi
        fi
    done
done
