#!/usr/bin/perl

use strict;
use warnings;

#use File::Temp qw/ tempfile/;

use IO::File;
use POSIX qw(tmpnam);

require '/usr/lib/localization-config/common/log.pl';

# Helper subroutine to set debconf key/value pairs
# This is to be called before installation of packages
# to preset the debconf values with useful values,
# according to the locale chosen by the user.

sub preseed {
    # The arguments needed are:
    # lang:            the locale value, used as key for the debconf arrays
    # debconf_keys:    the associative array with the names of the debconf keys
    #                  as used in /var/cache/debconf/config.dat
    # debconf_values:  the associative array with the actual values using locale
    #                  entry as key.

    my ($package, $debconf_values, $debconf_keys) = @_;

    # my ($tmpfile, $tmpfilename) = tempfile( UNLINK => 0, SUFFIX => '.txt' );

    my ($tmpfname, $tmpf);
    
    # try new temporary filenames until we get one that didn't already exist
    do { $tmpfname = tmpnam() }
        until $tmpf = IO::File->new($tmpfname, O_RDWR|O_CREAT|O_EXCL);
    
    # install atexit-style handler so that when we exit or die,
    # we automatically delete this temporary file
    END {
        if (defined($tmpfname)) {
            unlink($tmpfname) or log_die("$0:preseed(): Couldn't unlink $tmpfname : $!");
        }
    }
    
    # now go on to use the file ...
    
    # Debconf seeding for the given keys and values
    # the associative array debconf_keys holds the key names for
    # debconf, while the debconf_values holds the actual values,
    
    # Set debconf value for each given key/value pair
    for my $entry (sort keys %$debconf_keys) {
         if (defined($debconf_values->{$entry})) {
             log_msg("$0:preseed(): $entry\t$debconf_keys->{$entry}");
             log_msg("$0:preseed(): ".$debconf_keys->{$entry}." -> ".$debconf_values->{$entry});

             print $tmpf "$package $debconf_keys->{$entry} string $debconf_values->{$entry}\n";
        }
    }
       
    my $cmd;
    if ( -x "/usr/bin/debconf-set-selections") {
        $cmd = "/usr/bin/debconf-set-selections ".$tmpfname;
        system($cmd);
    } elsif ( -x "/usr/sbin/debconf-load-defaults") {
        $cmd = "/usr/sbin/debconf-load-defaults ".$tmpfname;
        
        system($cmd);
    }
    log_msg("$0:preseed(): executing $cmd");
    
    return;
}

1;
