#!/bin/sh
#
# ensure downloading sends progress as a regression test for commit 9127d7ae
#
set -e

TESTDIR="$(readlink -f "$(dirname "$0")")"
. "$TESTDIR/framework"

setupenvironment
changetohttpswebserver

assertprogress() {
    T="$1"
    testsuccess grep "dlstatus:1:0:Retrieving file 1 of 1" "$T"
    if ! grep -E -q "dlstatus:1:(0\..*|([1-9](\..*)?)|[1-9][0-9](\..*)?):Retrieving file 1 of 1" "$T"; then
        cat "$T"
        msgfail "Failed to detect download progress"
    fi
    testsuccess grep "dlstatus:1:100:Retrieving file 1 of 1" "$T"
}

# we need to ensure the file is reasonable big so that apt has a chance to
# actually report progress - but not too big to ensure its not delaying the
# test too much
TESTFILE=testfile.big
testsuccess dd if=/dev/zero of=./aptarchive/$TESTFILE bs=800k count=1

OPT='-o APT::Status-Fd=3 -o Debug::pkgAcquire::Worker=1 -o Debug::Acquire::http=1 -o Debug::Acquire::https=1'

msgtest 'download progress works via' 'http'
for i in 1 2 3 4 5 6 7 8 9 10; do
    exec 3> apt-progress-http.log
    testsuccess --nomsg apthelper download-file "http://localhost:${APTHTTPPORT}/$TESTFILE" ./downloaded/http-$TESTFILE $OPT -o Acquire::http::Dl-Limit=$((1600/i))
    if [ "$(wc -l  apt-progress-http.log | awk '{print $1}')" -ge 3 ]; then
        break
    fi
done
assertprogress apt-progress-http.log

msgtest 'download progress works via' 'https'
for i in 1 2 3 4 5 6 7 8 9 10; do
    exec 3> apt-progress-https.log
    testsuccess --nomsg apthelper download-file "https://localhost:${APTHTTPSPORT}/$TESTFILE" ./downloaded/https-$TESTFILE $OPT -o Acquire::https::Dl-Limit=$((1600/i))
    if [ "$(wc -l  apt-progress-https.log | awk '{print $1}')" -ge 3 ]; then
        break
    fi
done
assertprogress apt-progress-https.log

# cleanup
rm -f apt-progress*.log