#!/usr/bin/perl
# postinst script for pybit-client
# FIXME: port to use JSON as that is safe in a post-install script.
# see: dh_installdeb(1)

use strict;
use warnings;
use JSON;
use Debconf::Client::ConfModule qw(:all);
use vars qw/ $cfgfile %cfg @lines $json $json_hash $json_text %mapping /;
# summary of how this script can be called:
#        * <postinst> `configure' <most-recently-configured-version>
#        * <old-postinst> `abort-upgrade' <new version>
#        * <conflictor's-postinst> `abort-remove' `in-favour' <package>
#          <new-version>
#        * <postinst> `abort-remove'
#        * <deconfigured's-postinst> `abort-deconfigure' `in-favour'
#          <failed-install-package> <version> `removing'
#          <conflicting-package> <version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package

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

%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 ($ARGV[0] eq 'configure' or $ARGV[0] eq 'reconfigure') {
	if (-r "$cfgfile") {
		# read the edited values
		&ScanClientConfFile ($cfgfile);
		# set selected ones to update the debconf values.
		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');
			}
		}
	}
	$cfg{'clientid'}   = scalar get('pybit-client/clientid');
	$cfg{'host'} = scalar get('pybit-client/rabbitmqhost');
	$cfg{'dput_dest'} = scalar get('pybit-client/dputdest');
	$cfg{'buildroot'}  = scalar get('pybit-client/buildroot');
	$cfg{'use_lvm'}  = scalar get('pybit-client/lvmsnapshot');
	foreach my $key (keys %cfg) {
		my $val = $cfg{$key};
		chomp($val);
		$val =~ s/"//g;
		$val =~ s/'//g;
		$val =~ s/,//g;
		$cfg{$key} = $val;
	}
	if (-r "$cfgfile") {
		open(CONF, "$cfgfile") or die;
	} else {
		open(CONF, "/usr/share/pybitclient/client.conf") or die;
	}
	@lines=<CONF>;
	close (CONF);
	$json = new JSON;
	$json = $json->utf8(1);
	$json = $json->pretty(1);
	$json = $json->canonical(1);
	$json_text = join(' ', @lines);
	$json_hash = $json->decode($json_text);
	$$json_hash{'clientid'} = $cfg{'clientid'};
	$$json_hash{'host'} = $cfg{'host'};
	$$json_hash{'dput_dest'} = $cfg{'dput_dest'};
	$$json_hash{'buildroot'} = $cfg{'buildroot'};
	$$json_hash{'use_lvm'} = ($cfg{'use_lvm'} eq "true") ? JSON::true : JSON::false;
	if (not defined $$json_hash{'distribution'} or $$json_hash{'distribution'} !~ /\w/) {
		my $distro = `dpkg-vendor --query vendor`;
		chomp ($distro);
		$$json_hash{'distribution'} = $distro;
	}
	if (not defined $$json_hash{'pkg_format'} or $$json_hash{'pkg_format'} !~ /\w/) {
		$$json_hash{'pkg_format'} = "deb";
	}
	if (not defined $$json_hash{'host_arch'} or $$json_hash{'host_arch'} !~ /\w/) {
		my $host = `dpkg-architecture -qDEB_BUILD_ARCH 2>/dev/null`;
		chomp ($host);
		$$json_hash{'host_arch'} = $host;
	}
	$$json_hash{'debconf'} = JSON::true;
	open (CONF, ">$cfgfile") or die;
	print CONF $json->encode ($json_hash);
	close (CONF);
}

# 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>) {
		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;
}

my $dh_commands="set -- @ARGV\\n" . << 'EOF';
set -e

#DEBHELPER#
EOF

system ($dh_commands) / 256 == 0
	or die "Problem with shell scripts: $!";
exit 0
