#!/usr/bin/perl

use Debconf::Client::ConfModule qw(:all);
use File::Temp qw/ tempfile /;
use strict;
use warnings;
use vars qw / $username $cfile $workdir $aptagent $sources $suite 
$primary $noprimary $file $src @packageslist @sourcelist @ours  /;

$cfile = "/etc/emsource.conf";
$sources = "/etc/apt/sources.list.d/emdebian.sources.list";

version("2.0");
my $capb=capb("backup");

die ("postinst called with unknown argument.") if !$ARGV[0];

if ($ARGV[0] eq "configure")
{
	$workdir = get("emsource/workdir");
	$username = get("emsource/svnusername");
	$aptagent = get("emsetup/aptagent");
	$suite = get("emsource/targetsuite");
	(my $fh,$file) = tempfile();
	# despite using ucf, we can't rely on md5sums across different configurations
	# because the content of the file is autogenerated, not just the file itself.
	# this does make for a few more warnings from ucf than otherwise but that is
	# the price of preserving user changes.
	open (CFILE, ">$file") or die "Unable to create $file: $!\n";
	print CFILE "\# config file for emsource, part of emdebian-tools.\n";
	print CFILE "\# /etc/emsource.conf is maintained by debconf.\n";
	print CFILE "\# see emsource (1) for more information\n";
	print CFILE "\# \n";
	print CFILE "username: $username\n";
	print CFILE "workingdir: $workdir\n";
	print CFILE "targetsuite: $suite\n";
	print CFILE "aptagent: $aptagent\n";
	close (CFILE);
	system ("ucf --debconf-ok $file $cfile");
	system ("ucfr emdebian-tools $cfile");
	unlink ($file);
	chmod (0644, $cfile);
	$src = "";
	my %known=();
	# handle upgrades
	if ( -f $sources)
	{
		open EMDEBIAN, "$sources" or die "Unable to read existing $sources: $!";
		while (<EMDEBIAN>) {
			$src = $2 if (/^deb(\-src)? (.*) $suite main( non\-free)?( contrib)?$/);
			if ($src ne "") {
				$src =~ s/^(ht|f)tp:\/\///;
				$src =~ s/\/debian\/?$//;
				$known{$src}=1;
			}
			$src = "";
		}
		close EMDEBIAN;
	}
	@ours = keys %known;
	# if our file contains a primary, @exist contains that primary.
	my $exist = &primary_check(\@ours);
	# now check the main apt lists.
	# collate all available/configured sources into one list
	# OK to die here - if the file exists and root cannot open it, that is BAD!
	if (-e "/etc/apt/sources.list") {
		open (SOURCES, "/etc/apt/sources.list") or die "cannot open apt sources list. $!";
			# ensure we have a primary deb-src at the same time.
			while(<SOURCES>) {
				$src = $1 if (/^deb (.*) $suite main( non\-free)?( contrib)?$/);
				if ($src ne "") {
					$src =~ s/^(ht|f)tp:\/\///;
					$src =~ s/\/debian\/?$//;
					push @packageslist, $src;
				}
				$src = $1 if (/^deb\-src (.*) $suite main( non\-free)?( contrib)?$/);
				if ($src ne "") {
					$src =~ s/^(ht|f)tp:\/\///;
					$src =~ s/\/debian\/?$//;
					push @sourcelist, $src;
				}
				$src = "";
			}
		close (SOURCES);
	}
	if (-d "/etc/apt/sources.list.d/") {
		opendir (FILES, "/etc/apt/sources.list.d/") 
			or die "cannot open apt sources.list directory $!";
		my @files = grep(!/^\.\.?$/, readdir FILES);
		foreach my $f (@files) {
			next if ("/etc/apt/sources.list.d/$f" eq $sources);
			open (SOURCES, "/etc/apt/sources.list.d/$f") or 
				die "cannot open /etc/apt/sources.list.d/$f $!";
			# ensure we have a primary deb-src at the same time.
			while(<SOURCES>) {
				$src = $1 if (/^deb (.*) $suite main( non\-free)?( contrib)?$/);
				if ($src ne "") {
					$src =~ s/^(ht|f)tp:\/\///;
					$src =~ s/\/debian\/?$//;
					push @packageslist, $src;
				}
				$src = $1 if (/^deb\-src (.*) $suite main( non\-free)?( contrib)?$/);
				if ($src ne "") {
					$src =~ s/^(ht|f)tp:\/\///;
					$src =~ s/\/debian\/?$//;
					push @sourcelist, $src;
				}
				$src = "";
			}
			close (SOURCES);
		}
		closedir (FILES);
	}
	# now work out how many 'main' sources are primaries.
	my $apt = &primary_check(\@packageslist);
	my $apt_src = &primary_check(\@sourcelist);
	# if none, we must retain our own or set the default.
	# else no primary is set in our file and the system uses the apt one(s).
	if (scalar @$apt == 0)
	{
		$primary = "\# Emdebian requires at least one primary mirror. Use this one\n";
		$primary .= "\# OR add your preferred mirror to your apt sources,\n";
		$primary .= "\# run 'apt-get update', and then use:\n";
		$primary .= "\# dpkg-reconfigure emdebian-tools\n";
		$primary .= "\# See http://www.debian.org/mirror/list for a list of primary mirrors.\n";
		# $exist contains the previous selection of primary in the emdebian sourcelist file.
		if (scalar @$exist > 0) {
			foreach my $s (@$exist)
			{
				$primary .= "deb http://$s/debian $suite main\n";
			}
		} 
		else
		# no previous config, add a default primary.
		{
			$primary .= "deb http://ftp.uk.debian.org/debian $suite main\n";
		}
	}
	if (scalar @$apt_src == 0)
	{
		if (!defined($primary))
		{
			$primary = "\# Emdebian requires at least one primary mirror. Use this one\n";
			$primary .= "\# OR add your preferred mirror to your apt sources,\n";
			$primary .= "\# run 'apt-get update', and then use:\n";
			$primary .= "\# dpkg-reconfigure emdebian-tools\n";
			$primary .= "\# See http://www.debian.org/mirror/list for a list of primary mirrors.\n";
		}
		# $exist contains the previous selection of primary in the emdebian sourcelist file.
		if (scalar @$exist > 0) {
			foreach my $s (@$exist)
			{
				$primary .= "deb-src http://$s/debian $suite main\n";
			}
		} 
		else
		# no previous config, add a default primary.
		{
			$primary .= "deb-src http://ftp.uk.debian.org/debian $suite main\n";
		}
	}
	($fh,$file) = tempfile();
	open(SOURCES, ">$file") or die "Unable to create $sources: $!\n";
	print SOURCES "\# The Emdebian toolchain repository\n";
	print SOURCES "deb http://www.emdebian.org/debian/ $suite main\n";
	print SOURCES "deb-src http://www.emdebian.org/debian/ $suite main\n";
	print SOURCES "$primary\n" if (defined $primary);
	close (SOURCES);
	chmod (0644, $file);
	system ("ucf --debconf-ok $file $sources");
	system ("ucfr emdebian-tools $sources");
	unlink ($file);
	system ("/usr/bin/apt-key add /usr/share/emdebian-tools/0x97BB3B58.txt")
		if ( -x "/usr/bin/apt-key");
	stop;
}

sub primary_check
{
	my %checked=();
	my @primaries = qw/ ftp.at.debian.org ftp.au.debian.org ftp.wa.au.debian.org ftp.bg.debian.org ftp.br.debian.org ftp.ch.debian.org ftp.cl.debian.org ftp.cz.debian.org ftp.de.debian.org ftp2.de.debian.org ftp.dk.debian.org ftp.ee.debian.org ftp.es.debian.org ftp.fi.debian.org ftp.fr.debian.org ftp2.fr.debian.org ftp.uk.debian.org ftp.hk.debian.org ftp.hr.debian.org ftp.hu.debian.org ftp.ie.debian.org ftp.is.debian.org ftp.it.debian.org ftp.jp.debian.org ftp2.jp.debian.org ftp.kr.debian.org ftp.mx.debian.org ftp.nl.debian.org ftp.no.debian.org ftp.nz.debian.org ftp.pl.debian.org ftp.ro.debian.org ftp.ru.debian.org ftp.se.debian.org ftp.si.debian.org ftp.sk.debian.org ftp.tr.debian.org ftp.tw.debian.org ftp.us.debian.org /;
	$a = $_[0];
	foreach (@primaries) {
		$checked{$_}=1;
	}
	my @matches = grep ($checked{$_}, @$a);
	return \@matches;
}

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#
