#!/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
}

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

    printf  "Checking that no email is sent when nothing had to be done..."
    if ! chroot_exec "$chroot_dir" perl -MMIME::QuotedPrint -pe '$_=MIME::QuotedPrint::decode($_);' /var/mail/mail | grep -q "unattended and no pending auto-removals"; then
        echo "OK"
    else
        echo "FAILED, see last email above"
    fi

}
