#! /usr/bin/perl

=head1 NAME

printers - overview of printers

=head1 SYNOPSIS

 https://server/schulkonsole/printers

=head1 DESCRIPTION

C<printers> displays an overview of all printers and serves as a starting
point to select a printer for C<printers_edit>.
The HTML template is printers.tt.

=head2 Template variables

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

=over

=cut

use strict;
use utf8;
use lib '/usr/share/schulkonsole';
use Net::CUPS;
use Net::CUPS::Destination;
use Schulkonsole::Session;
use Schulkonsole::Files;


my $this_file = 'printers';



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 $cups = new Net::CUPS;
my @destinations = $cups->getDestinations();      # existing printers
my $printers = eval { Schulkonsole::Config::printers(); }; # configured printers
$printers = {} if $@;




my @printers_array;
foreach my $destination (@destinations) {
	my $printer = $destination->getName();

	if (exists $$printers{$printer}) {
		push @printers_array, {
				name => $printer,
				rooms => join(', ', sort keys %{ $$printers{$printer}{rooms} }),
				hosts => join(', ', sort keys %{ $$printers{$printer}{hosts} }),
			};
	} else {
		push @printers_array, {
				name => $printer,
			};
	}
}
@printers_array = sort { $$a{name} cmp $$b{name} } @printers_array;

=item C<printers>

The printers as an array of hashes with the keys

=over

=item C<name>

Name of the printer

=item C<rooms>

A comma separated list of rooms from where the printer can be accessed

=item C<hosts>

A comma separated list of hosts that can access the printer

=back

=cut

$sk_session->set_var('printers', \@printers_array);



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


=back

=head2 From fields

none
