#!/usr/bin/perl -w

# avoid using the JSON module here
# or get approval for a Pre-Depends in Debian.
# debconf config scripts may run before dependencies are fully configured
# in order to collect all debconf data in one run for later use by
# all the postinsts scripts for those packages.

use Debconf::Client::ConfModule qw(:all);

version("2.0");
capb("backup");

# basic structure borrowed from /var/lib/dpkg/info/dwww.config

my $cfgfile  = '/etc/pybit/client/client.conf';
my %cfg=();

my %mapping = ("clientid" => 'clientid',
	'use_lvm' => 'lvmsnapshot',
	'buildroot' => 'buildroot',
	'host' => 'rabbitmqhost',
	'dput_dest' => 'dputdest',
	'host_arch' => 'hostarch',
	'distribution' => 'distribution',
	'pkg_format' => 'pkgformat',
	'port' => 'rabbitport',
	'userid' => 'rabbituser',
	'vhost' => 'rabbitvhost',
	'dput' => 'dput_opt'
	);

if ( -r "$cfgfile" ) {
	# read any existing config file to avoid changing it
	&ScanClientConfFile ( "$cfgfile" );
	# set relevant values in debconf from any existing file
	foreach my $cfgvar ('clientid', 'use_lvm', 'host', 'buildroot', 'dput_dest', 'distribution') {
		if (defined $cfg{$cfgvar}) {
			set("pybit-client/$mapping{$cfgvar}",  $cfg{$cfgvar});
			fset("pybit-client/$cfgvar", 'seen', 'true');
		}
	}
}

my $state = 1;
while ($state > 0 && $state < 3) {
	if ($state == 1) {
		beginblock();
		# check for non-interactive frontends
		@ret = input('high', 'pybit-client/clientid');
		if ($ret[0] == 30) {
			# create some arbitrary defaults
			my $host = `hostname`;
			chomp ($host);
			set('pybit-client/clientid', $host);
			set('pybit-client/rabbitmqhost', 'localhost');
			set('pybit-client/dputdest', 'local');
			last;
		}
		input('high', 'pybit-client/rabbitmqhost');
		input('high', 'pybit-client/dputdest');
		endblock();
		@ret = go();

		# error handling
		$id = scalar get('pybit-client/clientid');
		chomp ($id) if defined ($id);
		while (($ret[0] == 0) and (not defined $id or $id =~ m/^\s*$/)) {
			fset('pybit-client/clientid', 'seen', 'false');
			fset('pybit-client/missingid', 'seen', 'false');
			beginblock();
			input('high', 'pybit-client/missingid');
			input('high', 'pybit-client/clientid');
			endblock();
			@ret = go();
			$id = scalar get('pybit-client/clientid');
			chomp ($id) if defined ($id);
		}
		set('pybit-client/clientid', $id);

		my $host = scalar get('pybit-client/rabbitmqhost');
		if (($ret[0] == 0) and (not defined $host or $host =~ m/^\s*$/)) {
			fset('pybit-client/rabbitmqhost', 'seen', 'false');
			fset('pybit-client/missinghost', 'seen', 'false');
			beginblock();
			input('high', 'pybit-client/missinghost');
			endblock();
			@ret = go();
			chomp ($host) if (defined $host);
			$host = scalar get('pybit-client/rabbitmqhost');
			$host = "" if not defined ($host);
		}
		set('pybit-client/rabbitmqhost', $host);

		my $dput = scalar get('pybit-client/dputdest');
		while (($ret[0] == 0) and (not defined $dput or $dput =~ m/^\s*$/)) {
			fset('pybit-client/dputdest', 'seen', 'false');
			fset('pybit-client/defaultdput', 'seen', 'false');
			beginblock();
			input('high', 'pybit-client/defaultdput');
			input('high', 'pybit-client/dputdest');
			endblock();
			@ret = go();
			chomp ($dput) if (defined $dput);
			$dput = scalar get('pybit-client/dputdest');
		}
		set('pybit-client/dputdest', $dput);
	}
	elsif ($state == 2) {
		beginblock();
		input('medium', 'pybit-client/lvmsnapshot');
		input('medium', 'pybit-client/buildroot');
		endblock();
		@ret = go();

		my $dir = scalar get('pybit-client/buildroot');
		chomp ($dir) if (defined $dir);
		if ($ret[0] == 0) {
			if ($dir =~ m|^/$| or not defined $dir or $dir eq '') {
				$dir = "/home/buildd/pybit";
			}
			mkdir_p ($dir);
		}
		set('pybit-client/buildroot', canondir($dir));
	}
	if ( ($ret[0] == 30) ) {
		$state--; 	# go back
	}
	else {
		$state++; 	# go forward
	}
}

# SUBROUTINES

# Subroutine to scan client configuration file
# Configfile to parse is the argument to the subroutine
sub ScanClientConfFile {
	if ( ! -r "$_[0]" ) { return; };
	open(CONFFILE,"<$_[0]") || die "Could not open $_[0]";
	while (<CONFFILE>) {
		# debconf values - keep the tag names the same as the debconf names
		foreach my $key (sort keys %mapping) {
			chomp;
			if (s#^\s*"$key"\s?:\s?(.*),?$#$1#) {
				chomp($cfg{$key} = $_) if /\w/;
			}
		}
	}
	foreach my $key (keys %cfg) {
		my $val = $cfg{$key};
		$val =~ s/"//g;
		$val =~ s/'//g;
		$val =~ s/,//g;
		$cfg{$key} = $val;
	}
	close CONFFILE;
}

sub canondir {
	my $dir = $_[0];
	$dir =~ s|/+|/|g;
	$dir =~ s|/$||;
	return $dir;
}

# Same as `mkdir -p'
sub mkdir_p {
	my $dir = shift;
	return if (-d $dir);
	my $p = "";
	foreach $f (split "/", $dir)  {
		$p .=  $f . "/";
		(-d $p) or (mkdir $p, 0755) or die "Can't create directory $p: $!\n";
	}
}
