#!/bin/sh
# verify and optionally save out the file
set -e

NOTEST=""
if [ "$1" = "--invalid" ]; then
	NOTEST=1
	shift
fi

file="$1"
saveto="$2"

if [ -n "$ROOT" ]; then
	chroot=chroot
else
	chroot=
fi

saveline () {
	if [ "$saveto" ]; then
		echo "$*" >> $saveto
	fi
}

valid () {
	line="$1"

	tmp=$($chroot $ROOT tempfile)
	echo "$line" > $ROOT$tmp
	
	# If the base system can be installed from CD, don't bother
	# validating the mirror; it can take a long time, most users won't
	# care just now, and the situation can be repaired later once the
	# system is installed.
	if [ -e /cdrom/.disk/base_installable ] || [ "$OVERRIDE_BASE_INSTALLABLE" ]; then
		case $line in
			'deb http'*|'deb ftp'*|'deb-src http'*|'deb-src ftp'*)
				rm -f $ROOT$tmp
				return 0
				;;
		esac
	fi

	if $chroot $ROOT apt-get -o APT::Get::List-Cleanup=false \
		-o Dir::Etc::sourcelist=$tmp update
	then
		rm -f $ROOT$tmp
	else
		rm -f $ROOT$tmp
		false
	fi
}

items=0
gooditems=0

IFS="
"
# Can't just iterate over $(cat $file) because that kills newlines, so
# introduce a dummy colon.
for line in $(sed 's/^/:/' $file); do
	line="${line#:}"
	if expr "$line" : '.*[^ ].*' >/dev/null && [ "$(expr "$line" : "#")" != 1 ]; then
		items=$(expr "$items" + 1)
		if [ -z "$NOTEST" ] && valid "$line"; then
			gooditems=$(expr "$gooditems" + 1)
			saveline "$line"
		else
			saveline "# Line commented out by installer because it failed to verify:"
			saveline "#$line"
		fi
	else
		saveline "$line"
	fi
done

if [ "$gooditems" != "$items" ]; then
	exit 1
fi
