#!/bin/sh

set -ex

chroot_dir=$AUTOPKGTEST_TMP/chroot
start_date=20200309T000000Z
end_date=20200328T000000Z
distro=sid

. debian/tests/common-functions

check_arch

UU_BUILDDEB_ARGS="-Zgzip" dpkg-buildpackage -us -uc 2>&1
do_debootstrap "$distro" "$chroot_dir" "http://snapshot.debian.org/archive/debian/$start_date/ unstable main"

sed -i 's/^deb /deb [check-valid-until=no] /' "$chroot_dir/etc/apt/sources.list"
echo "deb-src [check-valid-until=no] http://snapshot.debian.org/archive/debian/${start_date}/ $distro main" >> "$chroot_dir/etc/apt/sources.list"
chroot_exec "$chroot_dir" apt-get update

# install mailutils for testing u-u email
chroot_exec "$chroot_dir" apt-get install -y mailutils 2>&1

# add package set with many dependencies
# apt prints "W: APT had planned for dpkg to do more than it reported back" to stderr LP: #1647638
chroot_exec "$chroot_dir" apt-get install -y xfce4 2>&1

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

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

# hold a package to test if autoremoval honors that
chroot_exec "$chroot_dir" apt-mark hold libpython3.7-minimal

# also blacklist a package
echo 'Unattended-Upgrade::Package-Blacklist {"libgphoto2-.*"};' > \
     "$chroot_dir/etc/apt/apt.conf.d/51unattended-upgrades-blacklist"

# clean up to need less space for the test
chroot_exec "$chroot_dir" 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"

# use new snapshot
sed -i "s/$start_date/$end_date/" "$chroot_dir/etc/apt/sources.list"

run_u_u "$chroot_dir"

echo "Upgrade should be performed in minimal steps, checking that..."
grep -q "left to upgrade {" "$chroot_dir"/var/log/unattended-upgrades/unattended-upgrades.log || \
    (echo "FAILED: Upgrade was performed in a single step." ; exit 1)

echo "libpython3.7-minimal should be still installed and held:"
chroot_exec "$chroot_dir" dpkg -l libpython3.7-minimal | grep '^hi'

echo "libgphoto2-6 should be still installed and kept back thanks to the blacklist"
chroot_exec "$chroot_dir" dpkg -l libgphoto2-6 | grep '^ii.*2.5.23-2'
