#!/bin/sh
set -e

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

setupenvironment
configarchitecture "amd64"
configcompression 'gz'

insertpackage 'unstable' 'foo' 'amd64' '1'

setupaptarchive --no-update

testfailure aptcache show foo

# the Release file says gz available, but the mirror has only uncompressed files
find aptarchive/dists -name '*.gz' -delete

testsuccess apt update
testsuccess aptcache show foo
testfailure aptcache show bar

testsuccess apt update

rm -rf rootdir/var/lib/apt/lists


msgmsg 'File mirror was hacked'
mkdir aptarchive2
cp -a aptarchive/dists aptarchive2/
rm -rf rootdir/var/lib/apt/lists
find aptarchive/dists -name 'Packages' | while read FILE; do
	echo 'hacked' > $FILE
done
testfailure apt update -o Debug::pkgAcquire::Worker=1
testsuccessequal '4' grep -c -- '- Filesize:' rootdir/tmp/testfailure.output
testsuccessequal '2' grep -c '%0aAlt-Checksum-FileSize-Hash:%20' rootdir/tmp/testfailure.output

echo 'Acquire::By-Hash "force";' > rootdir/etc/apt/apt.conf.d/99force-by-hash.conf

msgmsg 'Fallback over hashsum errors'
rm -f rootdir/etc/apt/sources.list rootdir/etc/apt/sources.list.d/*
echo "deb mirror+file:${TMPWORKINGDIRECTORY}/mirror.list unstable main" > rootdir/etc/apt/sources.list
rm -rf rootdir/var/lib/apt/lists
cat > mirror.list <<EOF
copy:${TMPWORKINGDIRECTORY}/aptarchive	priority:1
file:${TMPWORKINGDIRECTORY}/aptarchive2	priority:2
EOF
testsuccess apt update
cp -a rootdir/tmp/testsuccess.output aptupdate.log
testsuccessequal '2' grep -c -- '^Ign:' aptupdate.log

rm -rf rootdir/var/lib/apt/lists
cat > mirror.list <<EOF
file:${TMPWORKINGDIRECTORY}/aptarchive	priority:1
copy:${TMPWORKINGDIRECTORY}/aptarchive2	priority:2
EOF
testsuccess apt update

rm -rf rootdir/var/lib/apt/lists
cat > mirror.list <<EOF
file:${TMPWORKINGDIRECTORY}/aptarchive	priority:1
file:${TMPWORKINGDIRECTORY}/aptarchive2	priority:2
EOF
testsuccess apt update
cp -a rootdir/tmp/testsuccess.output aptupdate.log
testsuccessequal '1' grep -c -- '^Ign:' aptupdate.log
