#!/bin/sh


check_arch() {
    local architecture
    architecture="$(dpkg --print-architecture)"
    # run test only on amd64 because it tests only Python code anyway
    case "$architecture" in
        amd64)
            echo "Running upgrade test on $architecture"
            ;;
        *)
            echo "Skipping upgrade test on $architecture"
            exit 0
            ;;
    esac
}

chroot_exec() {
    local chroot_dir
    chroot_dir="$1"
    shift

    chroot "$chroot_dir" env http_proxy="$http_proxy" eatmydata "$@"
}

do_debootstrap() {
    local chroot_dir distro mirror
    distro="$1"
    chroot_dir="$2"
    mirror="$3"

    debootstrap --include eatmydata,time "$@"

    mount --bind /dev/pts "$chroot_dir/dev/pts"
    mount --bind /proc "$chroot_dir/proc"
    trap "umount \"$chroot_dir/proc\"; umount \"$chroot_dir/dev/pts\"; rm -rf \"$chroot_dir\"" EXIT
}

rebuild_python_apt() {
    local chroot_dir
    chroot_dir="$1"

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

    (cd "$chroot_dir"/root/ && apt-get source python-apt 2>&1)
    chroot_exec "$chroot_dir" apt-get build-dep -y python-apt
    chroot_exec "$chroot_dir" bash -c "cd /root/python-apt-* && env DEB_BUILD_OPTIONS=nocheck dpkg-buildpackage -us -uc && apt-get install -y ../*.deb" 2>&1

    # remove packages installed as the side-effect of updating apt and python-apt
    chroot_exec "$chroot_dir" apt-mark showmanual | comm -1 -3 "$chroot_dir/tmp/manual" - | chroot_exec "$chroot_dir" xargs apt-mark auto
    chroot_exec "$chroot_dir" apt-get -y autoremove
    chroot_exec "$chroot_dir" apt-get clean
    rm "$chroot_dir"/tmp/manual
}

run_u_u() {
    local chroot_dir
    chroot_dir="$1"

    # let the test pass on battery power, too
    echo 'Unattended-Upgrade::OnlyOnACPower "false";' > "$chroot_dir/etc/apt/apt.conf.d/51unattended-upgrades-acpower"
    echo 'Unattended-Upgrade::Skip-Updates-On-Metered-Connections "false";' > "$chroot_dir/etc/apt/apt.conf.d/51unattended-upgrades-metered"

    # enable a few features to test

    echo 'Unattended-Upgrade::Mail "root";' > "$chroot_dir/etc/apt/apt.conf.d/51unattended-upgrades-mail"
    chroot_exec "$chroot_dir" apt-get update
    chroot_exec "$chroot_dir" unattended-upgrade --download-only
    chroot_exec "$chroot_dir" time unattended-upgrade --verbose --dry-run 2>&1
    chroot_exec "$chroot_dir" unattended-upgrade --verbose --debug
    chroot_exec "$chroot_dir" time unattended-upgrade --verbose 2>&1
    echo "new packages marked as manually installed (should be none): "
    chroot_exec "$chroot_dir" apt-mark showmanual | diff "$chroot_dir/tmp/manual" -
    chroot_exec "$chroot_dir" perl -MMIME::QuotedPrint -pe '$_=MIME::QuotedPrint::decode($_);' /var/mail/mail
}
