#!/usr/bin/perl -w
#------------------------------------------------------------------------------
# /var/config/www/cgi-bin/edit.pl - edit configuration
#
# Copyright (c) 2004  eisfair webconf team
#
# Creation:     10.10.2004
# Last Update:  $Id$
#
# 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.
#------------------------------------------------------------------------------

use strict;
use CGI::Carp qw(fatalsToBrowser);
use webconf_base;
use navigation;

use parse_checkfile;
use renderer_html;
use render_config;
use apply;

my @args = split(/&/,$ENV{'QUERY_STRING'});

my ($package, $stopstart, $title, $tempfile, $action) = ("", "", "", "", "");

foreach (0 .. $#args)
{
    if    ($args[$_] =~ /^package=(.*)/)   { $package   = decode_string($1); }
    elsif ($args[$_] =~ /^title=(.*)/)     { $title     = decode_string($1); }
    elsif ($args[$_] =~ /^tempfile=(.*)/)  { $tempfile  = "yes"; }
    elsif ($args[$_] =~ /^stopstart=(.*)/) { $stopstart = "yes"; }
}
if (!$title) { $title = "Edit $package configuration"; }

print_head($title, $package, "class=\"servform\"");
print_caption($title, $package, "class=\"servform\"");
print_navigation("base", "setup.menu", "setup.services.menu");


my %config;

### read html-form
my $form_string;
read(STDIN, $form_string, $ENV{CONTENT_LENGTH});
my @vars = split(/&/,$form_string);

foreach (0 .. $#vars)
{
    # decode MIME-encoded chars
    $vars[$_] =~ s/%0D//g;
    $vars[$_] = decode_string($vars[$_]);

    if    ($vars[$_] =~ /^action=\s*(.*)$/)  { $action = $1; $action =~ s/\s*$//; }
    elsif ($vars[$_] =~ /^([^=]*)=\s*(.*)$/) { $config{$1} = $2; }
}

### read config structure
my $structure = parse_checkfile($package);
my $renderer = create_renderer_html($package, "confform", $ENV{'QUERY_STRING'});

### now do it
if ($action eq "save & apply")
{
    print "<h2>Applying configuration ...</h2>\n";
    print "<div class=\"output\">";
    #  check, backup and save config
    if (save_config($package, $structure, \%config) == 0)
    {
        #  apply config
        apply_config($package, $stopstart);

        # re-read config
        %config = get_confvar($package);
    }
    print "</div>\n";
}
elsif ($action eq "refresh")
{
    # nothing - we display %config
}
else
{
    # read config
    %config = get_confvar($package);
}

render_config($renderer, $structure, \%config);

print_foot("class=\"servform\"");

