#!/usr/bin/perl
use IniConf;
use strict;

my $VERSION = 0.11;

my $inifile = "foo.ini"; # Hardcoded for security, for now
my $prog = "iniedit.cgi"; # The name of this file
my $cfg = IniConf->new(-file => $inifile);
my ($section, $param, $value, $name, $length);
my $form = FormParse();
PrintHeader();

#  Has the user already filled in some values?
if ($form->{action} eq "change")	{
	MakeChanges($form, $cfg);
}

# Display the HTML page
print qq~
<table>
<form action="$prog" method=POST>
<input type="hidden" name="action" value="change">
~;

for $section ($cfg->Sections)	{
	print "<tr><th colspan=2>$section</th></tr>\n";
	for $param	($cfg->Parameters($section))	{
		$value = $cfg->val($section, $param);
		$name = $section . "___" . $param;
		$length = length($value) + 5;
		print qq~
		<tr>
		 <td align=right>$param</td>
		 <td align=left><input name="$name" value="$value" size="$length"></td>
		</tr>
		~;
	}  #  End for param
} #  End for section

print qq~
	<tr><td colspan=2><input type=submit value="Make changes"></td>
	</form></table>
	~;

sub MakeChanges	{
	my ($form, $cfg) = @_;
	my ($key, $section, $param);

	for $key (keys %$form)	{
		if ($key =~ /___/)	{
			($section, $param) = split /___/, $key;
			$cfg->setval($section, $param, $form->{$key});
		}
	}  #  End keys

	$cfg->RewriteConfig;
	$cfg->ReadConfig;
}  #  End sub MakeChanges

sub FormParse  {
	my ($buffer,@pairs,$pair,$name,$value,$form);

	if ($ENV{REQUEST_METHOD} eq "POST")	{
		read (STDIN, $buffer, $ENV{CONTENT_LENGTH});
	}  else  {
		$buffer = $ENV{QUERY_STRING};
	}
	@pairs = split(/&/, $buffer);

	foreach $pair (@pairs)	{
    	($name, $value) = split(/=/, $pair);
    	$value =~ tr/+/ /;
    	$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
    	$value =~ s/~!/ ~!/g;

    	$form->{$name} = $value;
	}     # End of foreach

	return $form;
}	#  End of sub FormParse

sub PrintHeader	{
	print "Content-type: text/html\n\n";
}

=head1 NAME

iniedit.cgi - Interface for editing a generic ini configuration
file from the web.

=head1 DESCRIPTION

I often stick configuration options in a ini-type file, and then
provide a web interface for editing those options. This is the 
basic program for making those edits. I've put the form parsing
routine inline for the sake of having something that is almost
stand-alone, although it still uses IniConf for the ini file stuff.

=head1 PREREQUISITES

	C<strict>
	C<IniConf>

=pod OSNAMES

Any

=pod SCRIPT CATEGORIES

CGI

=cut

