#!/bin/bash

. ${TOOLKIT}-functions.sh


add_repo()
{
	local reponame=$1
	local desc=${2:-$reponame}
	local srcmatch="^[ ,	]*deb-src[ ,	]"
	local add_sources_here=false

	sourcefile="sources.list.$reponame"
	path=$(filepath $sourcefile) || exit_err 1 "$sourcefile missing"

	$add_sources && {
		add_sources_here=true
		grep -q "$srcmatch" $path || add_sources_here=false
	}

	if $add_sources
	then
		echo "  adding repos: $desc (with sources)"
		cat $path >>$outfile
	else
		echo "  adding repos: $desc"
		grep -v "$srcmatch" $path >>$outfile
	fi

	echo >>$outfile
	return 0
}


#----------------------------------------------------------------
# prepara sources.list
#----------------------------------------------------------------

outfile=sources.tmp

cp sources.list.header $outfile || exit $?

getconfirm install.add_sources		&& add_sources=true || add_sources=false


# first, despite the backup made by kusa-reconf itself, we
# save original sources.list in the same apt dir
#
file="/etc/apt/sources.list"
[ -f $file.orig ] || {
	echo "  saving actual source list into $file.orig"
	cp -a $file $file.orig || exit $?
}

# standard repos
#
if filepath sources.list.$DISTRIB_FULL_ID >/dev/null 2>&1
then
  add_repo $DISTRIB_FULL_ID	"$DISTRIB_FULL_ID $DISTRIB_CODENAME mirrors"
else
  add_repo $DISTRIB_ID		"$DISTRIB_ID $DISTRIB_CODENAME mirrors"
fi

case $DISTRIB_FULL_ID in
  Ubuntu-12.04)	add_repo "precise-backports" "Ubuntu-12.04 Backports" ;;
esac

add_repo "klabs"		"KUBiC Labs mirrors"

jtconf install.mirror_maintainer 2>/dev/null && {
	add_repo "maintainer"	"Maintainer mirrors"
}

# alix 
#
[ $KUSA_MODEL = "alix" ] && {
	add_repo "alix" "ALIX (Geode) mirrors"
}


# options local sources
#
file="sources.list.local"
path=$(filepath $file) 2>/dev/null || :
[ "$path" != "" ] && {
	add_repo "local" "LOCAL definitions ($path)"
	echo -e "\n# local sources (from: $path)\n" >>$outfile
	cat $path >>$outfile
}

exit 0
