#!/bin/sh
set -e

. /usr/share/debconf/confmodule
. /lib/debian-edu-common

logmsg() { logger -t debian-edu-install/apt-setup "$*"; }
log() { logmsg "info: $*"; }
error() { logmsg "error: $*"; }

at_exit() {
    error "script $0 terminated unexpectedly."
}
disable_exception() { trap - INT TERM EXIT; }
trap at_exit INT TERM EXIT

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


file="$1"

load_proxy_conf

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

# 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/$DISTRIBUTION/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"
	disable_exception
	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"

edu-etcvcs commit

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

disable_exception
exit 0
