#!/usr/bin/perl -w
use strict;
use Text::Template;

# This script reads variable assignments of the form var=value
# on STDIN, fills in a template given as the first argument
# with these values, and outputs the result on STDOUT.

# It is used by the maintainer scripts of request-tracker5
# to turn debconf variables into a valid RT_SiteConfig.pm
# snippet.

# Note that Text::Template is already a dependency of 
# request-tracker5, so it's OK to use it from the postinst.

# Copyright 2007 Niko Tyni <ntyni@iki.fi>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.  You may also can
# redistribute it and/or modify it under the terms of the Perl
# Artistic License.

my $template_file = shift;
die("usage: $0 <template>") if !$template_file;

my %values;

while (<>) {
    chomp;
    my ($var, $value) = split(/=/, $_, 2);
    if (!$var || not defined $value) {
        warn("Invalid input line: $_");
        next;
    }
    $values{$var} = $value;
}

my $template = Text::Template->new(
    TYPE    => 'FILE',
    SOURCE  => $template_file,
) or die ("Error reading template $template_file: $!");

my $result = $template->fill_in(HASH => \%values)
    or die("Error filling in the template: $Text::Template::ERROR");

print $result;

