#! /usr/bin/perl -w
#

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

#
#  The configuration file we use.
#
my $configFile = "/etc/gnump3d/gnump3d.conf";


#
# Test the file exists.
#
if ( ! -e $configFile )
{
    print "The configuration file '$configFile' doesn't exist.\n";
    print "aborting.\n";
    exit;
}


#
# Make sure we have permission to modify the file.
#
if ( ! -w $configFile )
{
    print "You don't have permission to write to '$configFile'.\n";
    print "aborting.\n";
    exit;
}


#
#  Read, modify, and write the config file contents.
#
my @lines = &getLines( $configFile );
@lines    = &modifyLines( @lines );
&writeLines( $configFile, @lines );
exit;


#
#  Read and return the contents of the gnump3d.conf file.
#
sub getLines($)
{
    my ($file) = (@_);

    open( CONF, "<$file" ) or die "Cannot open $file : $!";
    my @lines = <CONF>;
    close( CONF );

    return( @lines );
}


#
#  Modify the configuration file.
#
sub modifyLines(@)
{
    my (@lines) = (@_);
    my (@updated);

    # get debconf data
    my $port=get("gnump3d/port");
    my $root=get("gnump3d/root");
    my $user=get("gnump3d/user");
    my $logfile=get("gnump3d/logfile");

    foreach my $line ( @lines )
    {
	chomp( $line );

	#
	# Find and update the configuration options.
	#
	if ( $line =~ /^[^#]*port\s*=\s*(\S*)/ )
	{
	    $line = "port = $port";
	}
	if ( $line =~ /^[^#]*root\s*=\s*(\S*)/ )
	{
	    $line = "root = $root";
	}
	if ( $line =~ /^[^#]*user\s*=\s*(\S*)/ )
	{
	    $line = "user = $user";
	}
	if ( $line =~ /^[^#]*logfile\s*=\s*(\S*)/ )
	{
	    $line = "logfile = $logfile";
	}


	push @updated, $line . "\n";
    }
    return( @updated );
}

#
#  Write the given array to the config file.
#
sub writeLines($@)
{
    my ($file,@contents) = (@_);

    open( CONF, ">$file" ) or die "Cannot open $file : $!";
    print CONF @contents;
    close( CONF );
}
