#!/bin/sh
set -e

TESTDIR="$(readlink -f "$(dirname "$0")")"
. "$TESTDIR/framework"
setupenvironment
configarchitecture 'amd64'

buildsimplenativepackage 'unrelated' 'all' '0.5~squeeze1' 'unstable'
buildsimplenativepackage 'unrelated2' 'all' '0.5~squeeze1' 'unstable'
insertinstalledpackage 'unrelated2' 'all' '0.1'

setupaptarchive --no-update
changetowebserver -o aptwebserver::redirect::replace::/pool/=/newpool/ \
		  -o aptwebserver::redirect::replace::/dists/=/newdists/

mv aptarchive/pool aptarchive/newpool
mv aptarchive/dists aptarchive/newdists

testrun() {
	msgmsg "Test $1 redirection works in method boundaries" "$2"
	msgtest 'Test redirection works in' 'apt-get update'
	testsuccess --nomsg aptget update

	# check that I-M-S header is kept in redirections
	testsuccessequal "Hit:1 $2 unstable InRelease
Reading package lists..." aptget update

	msgtest 'Test redirection works in' 'package download'
	testsuccess --nomsg aptget install unrelated --download-only -y
}

for CODE in 301 302 307; do
	webserverconfig 'aptwebserver::redirect::httpcode' "$CODE"
	rm -f aptarchive/webserver.log.client*.log
	testrun "$CODE" "http://localhost:${APTHTTPPORT}"
	testsuccess grep "^HTTP/1.1 $CODE " aptarchive/webserver.log.client*.log
	rm -rf rootdir/var/lib/apt/lists rootdir/var/cache/apt/archives
done

changetohttpswebserver

for CODE in 301 302 307; do
	webserverconfig 'aptwebserver::redirect::httpcode' "$CODE"
	rm -f aptarchive/webserver.log.client*.log
	testrun "$CODE" "https://localhost:${APTHTTPSPORT}"
	testsuccess grep "^HTTP/1.1 $CODE " aptarchive/webserver.log.client*.log
	rm -rf rootdir/var/lib/apt/lists rootdir/var/cache/apt/archives
done

testsuccess apt update
testsuccess aptget install unrelated --download-only
testsuccessequal 'Reading package lists...
Building dependency tree...
Calculating upgrade...
The following NEW packages will be installed:
  unrelated
The following packages have been kept back:
  unrelated2
0 upgraded, 1 newly installed, 0 to remove and 1 not upgraded.
Inst unrelated (0.5~squeeze1 unstable [all])
Conf unrelated (0.5~squeeze1 unstable [all])' aptget dist-upgrade unrelated --no-download --fix-missing -s
testsuccess aptget dist-upgrade unrelated --no-download --fix-missing -y
testdpkginstalled unrelated