#!/bin/sh

set -e

chroot_dir=$AUTOPKGTEST_TMP/chroot
start_date=20171001T000000Z
end_date=20171210T000000Z
chroot_exec="chroot $chroot_dir eatmydata"

dpkg-buildpackage -us -uc 2>&1
debootstrap --include eatmydata sid $chroot_dir "http://snapshot.debian.org/archive/debian/$start_date/ unstable main"
mount --bind /dev/pts $chroot_dir/dev/pts
sed -i 's/^deb /deb [check-valid-until=no] /' $chroot_dir/etc/apt/sources.list
$chroot_exec apt-get update

# install mailutils for testing u-u email and mark python3.5-minimal
# because otherwise u-u autoremoves it while running python3.5 code
$chroot_exec apt-get install -y python3.5-minimal mailutils

# add package set with many dependencies
$chroot_exec apt-get install -y xfce4

# install package version just built
cp ../unattended-upgrades_*.deb $chroot_dir/tmp/
$chroot_exec bash -c 'apt install -y /tmp/unattended-upgrades_*deb' 2>&1

# save list of manually installed packages
$chroot_exec apt-mark showmanual > $chroot_dir/tmp/manual

# clean up to need less space for the test
$chroot_exec apt-get clean

# install Debian's configuration file to make this test work as expected even on other distributions
cp data/50unattended-upgrades.Debian $chroot_dir/etc/apt/apt.conf.d/50unattended-upgrades

# enable a few features to test
sed -i 's|//Unattended-Upgrade::Mail |Unattended-Upgrade::Mail |' $chroot_dir/etc/apt/apt.conf.d/50unattended-upgrades
sed -i "s/$start_date/$end_date/" $chroot_dir/etc/apt/sources.list
$chroot_exec apt-get update
$chroot_exec unattended-upgrade --verbose
echo "new packages marked as manually installed (should be none): "
$chroot_exec apt-mark showmanual | diff $chroot_dir/tmp/manual -
$chroot_exec perl -MMIME::QuotedPrint -pe '$_=MIME::QuotedPrint::decode($_);' /var/mail/mail
# cleanup
umount $chroot_dir/dev/pts
rm -rf $chroot_dir
