#! /bin/bash

set -ex

# Enable a console on ttyS0 so that we can log-in via vm-run.
#
echo 'GRUB_CMDLINE_LINUX="console=ttyS0,115200"' >>/etc/default/grub
update-grub

# We install all dependencies of the cockpit packages since we want
# them to not spontaneously change from one test run to the next when
# the distribution repository is updated.
# docker.io \
#
COCKPIT_DEPS="\
cryptsetup \
libjson-glib-1.0-0 \
libpcp3 \
libpolkit-gobject-1-0 \
libpwquality-tools \
libssh-4 \
libvirt-daemon-system \
mdadm \
network-manager \
pcp \
policykit-1 \
realmd \
selinux-basics \
thin-provisioning-tools \
xdg-utils \
udisks2 \
"

TEST_PACKAGES="\
curl \
gdb \
virtinst \
xfsprogs \
"

useradd -m -U -c Administrator -G sudo -s /bin/bash admin
echo admin:foobar | chpasswd

export DEBIAN_FRONTEND=noninteractive
eatmydata apt-get -y install $TEST_PACKAGES $COCKPIT_DEPS

# Install docker separately from jessie-backports
echo "deb http://deb.debian.org/debian jessie-backports main" >/etc/apt/sources.list.d/backports.list
apt-get -y update
eatmydata apt-get -y install docker.io
rm /etc/apt/sources.list.d/backports.list
apt-get -y update

# Prepare for building
#

# extract control files and adjust them for our release, so that we can parse the build deps
mkdir -p /tmp/out
tar -C /tmp/out --strip-components=1 --wildcards -xf "$TEST_SOURCE" '*/debian/'
/tmp/out/tools/debian/adjust-for-release $(lsb_release -sc)

# Disable build-dep installation for the real builds
cat > ~/.pbuilderrc <<- EOF
DISTRIBUTION=jessie
PBUILDERSATISFYDEPENDSCMD=true
EOF

eatmydata apt-get -y install dpkg-dev pbuilder

pbuilder --create
/usr/lib/pbuilder/pbuilder-satisfydepends-classic --control /tmp/out/tools/debian/control --force-version --echo|grep apt-get | pbuilder --login --save-after-login
rm -rf /tmp/out

# Debian does not automatically start the default libvirt network
virsh net-autostart default

# HACK: docker falls over regularly, print its log if it does
systemctl start docker || journalctl -u docker

# docker images that we need for integration testing
/var/lib/testvm/docker-images.setup

# in case there are unnecessary packages
apt-get -y autoremove || true

# reduce image size
apt-get clean
/var/lib/testvm/zero-disk.setup

# Final tweaks

# Enable persistent journal
mkdir /var/log/journal

# Allow root login with password
sed -i 's/^[# ]*PermitRootLogin .*/PermitRootLogin yes/' /etc/ssh/sshd_config

# HACK: https://bugzilla.mindrot.org/show_bug.cgi?id=2512
# Disable the restarting of sshd when networking changes
ln -snf /bin/true /etc/network/if-up.d/openssh-server
