#!/usr/bin/perl

if (@ARGV != 3)
{
    print STDERR "USAGE:addsetting VARIABLE VALUE FILE\n";
    exit(1);
}

$var = shift @ARGV;
$value = shift @ARGV;
$file = shift @ARGV;

if (! -f $file)
{
    print STDERR "$file does not exist\n";
    exit(1);
}

system("rm -f $file.bak");
system("cp $file $file.bak");

open(FILE,$file) or die "Can't open $file for reading.";
foreach(<FILE>)
{
    chomp();
    push @lines,$_;
}
close(FILE);

$nextquote=0;
foreach(@lines)
{
    if (/$var\s*=/)
    {
	$nextquote=1;
    }
    if ($nextquote)
    {
	if (/"/)
	{
	    s/"/" $value /;
	    $nextquote=0;
	}
    }
}

open(FILE,">".$file) or die "Can't open $file for writing.";
foreach(@lines)
{
    print FILE $_."\n";
}
close(FILE);
