#!/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"

# 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
test "$MIRROR" || exit 0 

# 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 "deb http://ftp.no.debian.org/debian $codename $dists" >> $file
