#!/bin/bash

. ${TOOLKIT}-functions.sh

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

	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 >$tmpfile
	else
		echo "  adding repos: $desc"
		grep -v "$srcmatch" $path >$tmpfile
	fi

	installfile $tmpfile /etc/apt/sources.list.d/$reponame.list root:root 444
	return 0
}

#----------------------------------------------------------------
# need to install custom sources.list?
#----------------------------------------------------------------
case $DISTRIB_ID in
  Devuan)
	installfile sources.tmp		/etc/apt/sources.list root:root 444
	;;
esac


# check alix gpg key
#
[ $KUSA_MODEL = "alix" ] && {
	apt-key list | grep -q 'Voyage Linux' || {
		keyurl=$(jtconf install.key_alix 2>/dev/null)
		[ "$keyurl" != "" ] && {
			keyfile=$(echo $keyurl | sed -e 's#.*/##')
			wgetfile $keyurl
			echo -n "adding Alix key to apt ... "
			apt-key add $keyfile
		}
	}
}


#----------------------------------------------------------------
# add / removes listfiles in /etc/apt/sources.list.d
#----------------------------------------------------------------

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


add_repo_d "klabs"		"KUBiC Labs mirrors"

if jtconf install.mirror_maintainer 2>/dev/null
then
	add_repo_d "maintainer"	"Maintainer mirrors"
else
	uninstallfiles --remove /etc/apt/sources.list.d/maintainer.list
fi

# alix 
#
if [ $KUSA_MODEL = "alix" ]
then
	add_repo_d "alix" "ALIX (Geode) mirrors"
else
	uninstallfiles --remove /etc/apt/sources.list.d/alix.list
fi


file="sources.list.local"
path=$(filepath $file) 2>/dev/null || :
if [ "$path" != "" ]
then
	add_repo_d "local" "LOCAL definitions ($path)"
else
	uninstallfiles --remove /etc/apt/sources.list.d/local.list
fi


# cleanup obsolete files
#
uninstallfiles /etc/apt/apt.conf.d/50apt-kusa-allow-unauth


$SOMETHING_CHANGED && {
	echo -en "  repos changed "
	update_repos || exit $?
	echo "ok"
}
exit 0
