#!/bin/sh

##
## KatolaZ -- 20171105
##

##
## Test rewrite rules for Devuan package mirrors.
## Please provide as first argument the BaseURL of the mirror, 
## i.e., the URL to be put in sources.list (everything that must 
## be found after "deb" and before "/merged/")
##
## If the second parameter "as-host" is specified,  add the header
## "Host: $as-host" to the request (useful to check mirrors in the 
## deb.devuan.org Round-Robin)
##
##
##


MAXTIME=20

if [ $# -lt 1 ]; then 
	echo "Usage: $0 <BaseURL> [<as-host>]"
	echo "(Example: $0 http://pkgmaster.devuan.org)"
	exit 1
fi


## we need either curl or wget...

if [ -z "$(which wget)" -a -z "$(which curl)" ]; then 
	echo "Error! Cannot find either 'curl' or 'wget'"
	exit 2		
fi

## ...but we prefer curl, if present

CURL=$(which curl)
if [ -n "$CURL" ]; then
	HTTP_CLIENT="$CURL"
	HTTP_OPTS="-s -L -f -m ${MAXTIME}"
	HTTP_ADD_HEADER="--header "
else
	HTTP_CLIENT=$(which wget)
	HTTP_OPTS="-q -O - -T ${MAXTIME}"
	HTTP_ADD_HEADER="--header="
fi


if [ $# -gt 1 ]; then
	AS_HOST="${HTTP_ADD_HEADER}\"Host: $2\""
else
	AS_HOST=""
fi

echo "Using ${HTTP_CLIENT} -- AS_HOST: ${AS_HOST}"


BASEURL="$1"

## These packages are all in Devuan jessie
DEVUAN_PKG="${BASEURL}/merged/pool/DEVUAN/main/b/base-files/base-files_8+devuan7_amd64.deb"
DEBIAN_PKG="${BASEURL}/merged/pool/DEBIAN/main/d/dash/dash_0.5.7-4+b1_amd64.deb"
DEBSEC_PKG="${BASEURL}/merged/pool/DEBIAN-SECURITY/updates/main/a/apache2/apache2_2.4.25-3+deb9u7_amd64.deb"
DEBINST_PKG="${BASEURL}/merged/pool/DEBIAN/main/l/linux/btrfs-modules-4.9.0-9-amd64-di_4.9.168-1_amd64.udeb"


TOT_ERR=0


for type in DEVUAN_PKG DEBIAN_PKG DEBSEC_PKG DEBINST_PKG; do 
	eval "type_deb=\${$type}"
	type_name=$(echo ${type} | cut -d "_" -f 1)
	printf "Trying ${type_name} package (${type_deb})..."
	##echo "Issuing command: ${HTTP_CLIENT} ${HTTP_OPTS} ${AS_HOST} ${type_deb}"
	eval ${HTTP_CLIENT} ${HTTP_OPTS} ${AS_HOST} ${type_deb} > /dev/null
	ret="$?"
	echo "ret: $ret"
	if [ "$ret" = "0" ]; then 
		echo "[\033[32mOK\033[0m]"
	else
		echo "[\033[31mFAILED\033[0m]"
		TOT_ERR=$((${TOT_ERR} + 1))
	fi
done

echo "=======" 

if [ "${TOT_ERR}" = "0" ]; then 
       echo "Rewrites are OK" && exit 0
else
	echo "There are ${TOT_ERR} rewrite errors -- Please recheck!!!" && exit ${TOT_ERR}

fi