#!/bin/sh
set -e

. /usr/share/debconf/confmodule

log() {
    logger -t aptsetup-de "info: $*"
}

log "Doing som apt-source magic for Debian-Edu"


file="$1"

# Prevent installer to contact security host as we don't have network
# connection.  Setting apt-setup/security_host to an empty value will
# make apt-setup/generators/90security skip the security mirror
if ! wget -qO - http://security.debian.org/dists/etch/updates/Release ; then
	log "Disabling security mirror, unable to reach it using http/wget"
	db_fset apt-setup/security_host seen true || true
	db_set apt-setup/security_host "" || true
else
	log "Not touching security mirror settings, able to reach it using http/wget"
fi

# Fetch the mirror 
db_get mirror/http/hostname || true
MIRROR=$RET

# if this is a CD-based install, assume that we dont need more apt-sources
if test "$MIRROR" ; then
	log "Mirror set, running apt-setup override for debian-edu"
else
	log "No mirror set, not running apt-setup override for debian-edu"
	exit 0
fi

# To determine if non-free and contrib should be included, grep
# the file to see if they are listed in it.
dists="main"
for dist in contrib non-free; do
	if grep -q '^[^#]*'$dist $ROOT/etc/apt/sources.list.new; then
		dists="$dists $dist"
	fi
done

# mirror/codename is also set by cdrom methods
db_get mirror/codename || true
codename="$RET"

# if a country is selected for mirror, then I guess we can continue without adding an official mirror
db_get mirror/country || true
if [ "$RET" != "enter information manually" ] ; then 
    exit 0
fi

# We need to check for a local repository if we are using http as source
db_get mirror/protocol || true
if [ "$RET" = "http" ] ; then 
    log "OK found http_protocol"
    db_get mirror/http/directory || true
    if wget -qO - http://$MIRROR$RET/dists/$codename/Release | grep -q " local/binary" ; then 
        log "OK, Found local/binary, adding to $file"
        echo "deb http://$MIRROR$RET $codename local" >> $file
    fi
fi

echo "# you can replace ftp.skolelinux.no with ftp.no.debian.org or any other" >> $file
echo "# debian mirror:" >> $file
echo "deb http://ftp.skolelinux.no/debian $codename $dists" >> $file
echo "deb http://ftp.skolelinux.no/skolelinux etch-test local" >> $file
