#! /usr/bin/perl

=head1 NAME

settings repair - produces page for repair settings

=head1 SYNOPSIS

 https://server/schulkonsole/settings_repair

=head1 DESCRIPTION

C<settings_repair> produces the page of repair settings.
The HTML template is settings_repair.tt.

=head2 Template variables

Additionally to the variables of Schulkonsole::Session C<settings_repair>
provides the following variables:

=over

=cut

use strict;
use utf8;
use lib '/usr/share/schulkonsole';
use Schulkonsole::Config;
use Schulkonsole::Session;
use Schulkonsole::Files;


my $this_file = 'settings_repair';

my $sk_session = new Schulkonsole::Session($this_file);
if (not $sk_session->get_password()) {
	my $q = new CGI;
	my $url = $q->url( -full => 1 );

	# we send cookies over secure connections only
	if ($url =~ s/^http:/https:/g) {
		$sk_session->redirect($url);
	} else {
		$sk_session->exit_with_login_page($this_file);
	}
}

my $q = $sk_session->query();


my $id = $sk_session->userdata('id');
my $password = $sk_session->get_password();

COMMANDS: { 
	eval {
		if ($q->param('accept')) {
			my %new_programs;
			my %params = $q->Vars;
			foreach (keys %params) {
				my ($key,$mark) = $_ =~ /^(.+)(_name)$/;
				next unless $key && $mark;
				$new_programs{$key}{'name'} = $q->param($_);
			}
			foreach (keys %new_programs) {
				my @values = $q->param($_ . '_value');
				next unless scalar @values;
				push @{$new_programs{$_}{'paths'}}, @values;
			}
			foreach (keys %new_programs) {
				delete $new_programs{$_} unless $new_programs{$_}{paths};
			}
			my %repair;
			foreach (keys %new_programs) {
				$repair{$new_programs{$_}{name}} = join(',', @{$new_programs{$_}{paths}});
			}
			my $lines = Schulkonsole::Config::new_preferences_lines($Schulkonsole::Config::PATHPREFS, \%repair);
			Schulkonsole::Files::write_preferences_conf_file($id, $password, $lines);
			
			$sk_session->set_status($sk_session->d()->get('Änderungen übernommen'), 0);
		}
	};
} # COMMANDS
if ($@) {
	$sk_session->standard_error_handling($this_file, $@);
}


=item C<cprogram>

A hash of arrays of program paths.

$program {
	program1 => [
		path1,
		path2,
		path3,
		...
	],
	program2 => [
		path1,
		...
	],
	...
}

=cut

$sk_session->set_var('program', \%Schulkonsole::Config::_repair_path);

$sk_session->print_page("$this_file.tt", $this_file);

=back

=head2 Form fields

=over

=item C<accept>

Write the changes

=cut
