#!/usr/bin/perl -w

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 @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");
	# Reading the dpkg-cross debconf default would require a Pre-Depends on dpkg-cross.
	# apt is already a Pre-Depends, so assume arm as the test arch.
	(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 "aptagent: $aptagent\n";
	close (CFILE);
	system ("ucf --debconf-ok $file $cfile");
	system ("ucfr emdebian-tools $cfile");
	unlink ($file);
	$suite = &get_suite;
	$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$/);
			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 list.
	open POLICY, "/etc/apt/sources.list" or die "Unable to read apt list: $!";
	while (<POLICY>) {
		$src = $2 if (/^deb(\-src)? (.*) $suite main$/);
		if ($src ne "") {
			$src =~ s/^(ht|f)tp:\/\///;
			$src =~ s/\/debian\/?$//;
			push @sourcelist, $src;
		}
		$src = "";
	}
	close POLICY;
	# now work out how many 'main' sources are primaries.
	my $apt = &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 /etc/apt/sources.list\n";
		$primary .= "\# and then use dpkg-reconfigure emdebian-tools\n";
		$primary .= "\# See http://www.debian.org/mirror/list for a list of primary mirrors.\n";
		if (scalar @$exist > 0) {
			foreach my $s (@$exist)
			{
				$primary .= "deb http://$s/debian $suite main\n";
				$primary .= "deb-src http://$s/debian $suite main\n";
			}
		} 
		else 
		{
			$primary .= "deb http://ftp.uk.debian.org/debian $suite main\n";
			$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);
	stop;
}

sub get_suite()
{
	my ($cur_pri, $max_pri, $max_pri_suite);
	# list of suites supported by Emdebian toolchain repository.
	my @suites = qw/unstable testing stable sid etch/;
	# Improved to detect priority. Ben Hutchings <ben@decadent.org.uk>
	open POLICY, "apt-cache policy |" or die "Unable to read apt policy: $!";
	for (<POLICY>) {
	    if (/^\s*(\d+)/) {
		$cur_pri = $1;
	    } elsif (defined($cur_pri)
		     && (!defined($max_pri) || $cur_pri > $max_pri)
		     && /^\s+release o=Debian,a=(\w+),l=Debian,c=main\s*$/) {
		$max_pri = $cur_pri;
		$max_pri_suite = $1;
	    }
	}
	close POLICY;
	if (defined($max_pri_suite)) {
		$suite = $max_pri_suite;
	} else {
		die ("Unable to determine apt-cache policy for Debian main!");
	}
	foreach my $s (@suites)
	{
		# check the matched value is sensible.
		return $s if ($suite eq $s);
	}
	die ("Unable to use current suite: $suite is unsupported in Emdebian!");
}

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#
