#! /usr/bin/perl

=head1 NAME

project_handout - hand out files to project

=head1 SYNOPSIS

 https://server/schulkonsole/project_handout

=head1 DESCRIPTION

C<project_handout> lets you hand out files to a selected project.
The HTML template is project_handout.tt.

=head2 Template variables

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

=over

=cut

use strict;
use utf8;
use lib '/usr/share/schulkonsole';
use Schulkonsole::Session;
use Schulkonsole::Info;
use Schulkonsole::Sophomorix;
use File::Basename;

my $this_file = 'project_handout';
my $transfername = 'handout_project';

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 $d = $sk_session->d();

my $projects = Schulkonsole::Info::groups_projects($sk_session->groups());



my $project = $q->param('projects');
if (    $project
    and $$projects{$project}) {
	$sk_session->param('project', $project);
}
$project = $sk_session->param('project');

if (   not $project
    or not $$projects{$project}) {
	my $url = $q->url( -absolute => 1 );
	$url =~ s/$this_file$/project/g;
	$sk_session->param('requested_page',$this_file);
	$sk_session->redirect($url);
}

if (not Schulkonsole::DB::is_project_admin($$projects{$project}{id},
        	$sk_session->userdata('uidnumber'))) {
	$sk_session->set_status_redirect($sk_session->d()->get(
		'Sie sind kein Projektleiter'),
		1);

	my $url = $q->url( -absolute => 1 );
	$url =~ s/$this_file$/project_members/g;
	$sk_session->redirect($url);
}




eval {
	SWITCHCOMMAND: {
		$q->param('handout') and do {
			eval {
			Schulkonsole::Sophomorix::handout_project($sk_session->userdata('id'),
				$sk_session->get_password(),
				$project);
		
			$sk_session->set_status(
				$sk_session->d()->get('Vorlagen bereitgestellt'), 0);
			};

			last SWITCHCOMMAND;
		};
		
		$q->param("upload_$transfername") and do {
			my $file = $q->param("upload_$transfername");
			utf8::decode($file);
			my $tmpfile = "$Schulkonsole::Config::_runtimedir/upload_${transfername}_"
							. $sk_session->session_id() . '_' . time;
			if(! open(DAT,'>'.$tmpfile)) {
				$sk_session->set_status($d->get('Es konnte keine temporäre Datei erzeugt werden.'),1);
				last SWITCHCOMMAND;
			}
			binmode($file);
			binmode(DAT);
			my $buffer = "";
			while( read($file, $buffer, 1024)) {
				print DAT $buffer;
			}
			close(DAT);
			my $filename = basename($file);
			
			Schulkonsole::Sophomorix::add_handout_project(
				$sk_session->userdata('id'), $sk_session->get_password(), $project, $filename, 0, basename($tmpfile));
			$sk_session->set_status($d->get('Datei hochgeladen'),0);
			
			last SWITCHCOMMAND;	
		}; 
		
		foreach my $param ($q->param) {
			if (my ($file, $action)
			    	= $param =~ /^(.+);(delete|download)$/) {
				utf8::decode($file);
				my $admin_share_files = Schulkonsole::Sophomorix::ls_handout_project(
						$sk_session->userdata('id'), $sk_session->get_password(), $project);
				
				SWITCHACTION: {
				$action =~ /delete/ and do {
					if(not defined $$admin_share_files{$file}) {
						$sk_session->set_status(
							$d->get('Datei ') . $file . $d->get(' nicht als bereitzustellende Datei vorhanden.'), 1);
						last SWITCHACTION;
					}
					Schulkonsole::Sophomorix::rm_handout_project(
						$sk_session->userdata('id'), $sk_session->get_password(), $project,
						$file, ($$admin_share_files{$file}?1:0));
					
					$sk_session->set_status($d->get('Datei gelöscht.'),0);
					
					last SWITCHACTION;
				};
				
				$action =~ /download/ and do {
					if(not defined $$admin_share_files{$file}) {
						$sk_session->set_status(
							$d->get('Datei ') . $file . $d->get(' nicht als bereitzustellende Datei vorhanden.'),	1);
						last SWITCHACTION;
					}
					my $tmpfile = "download_${transfername}_".$sk_session->session_id() . '_' . time;
					
					Schulkonsole::Sophomorix::dl_handout_project(
						$sk_session->userdata('id'), $sk_session->get_password(), $project,
						$file, ($$admin_share_files{$file}?1:0), $tmpfile);
					
					if( -e "$Schulkonsole::Config::_runtimedir/$tmpfile") {
						print $q->header( -type           => "application/x-download",
								          -attachment     => $file,
										   -Content_length => -s "$Schulkonsole::Config::_runtimedir/$tmpfile");
									
						if(! open(FILE, "<$Schulkonsole::Config::_runtimedir/$tmpfile")) {
							$sk_session->set_status($d->get('Die temporäre Datei konnte nicht geöffnet werden.'), 1);
							last SWITCHCOMMAND;
						}
						binmode(FILE);
						binmode(STDOUT);
						print while <FILE>;
						if(!close(FILE)) {
							$sk_session->set_status($d->get('Die temporäre Datei konnte nicht geschlossen werden.'), 1);
							last SWITCHCOMMAND;
						}
						
						if($$admin_share_files{$file}){
							system("rm -rf $Schulkonsole::Config::_runtimedir/$tmpfile");
						} else {
							system("rm -f $Schulkonsole::Config::_runtimedir/$tmpfile");
						}
		
						$sk_session->set_status($d->get('Die Datei wurde heruntergeladen.'), 0);
						exit 0;
						
					} else {
						$sk_session->set_status($d->get('Es konnte keine temporäre Datei erzeugt werden.'), 1);
						last SWITCHCOMMAND;				
					}
					
					last SWITCHACTION;
				};
				
				} #SWITCHACTION
			}
		} # foreach param

	} # SWITCHCOMMAND
}; # eval

if ($@) {
	$sk_session->standard_error_handling($this_file, $@);
}







eval {
my $admin_share_files = Schulkonsole::Sophomorix::ls_handout_project(
	$sk_session->userdata('id'),
	$sk_session->get_password(),
	$$projects{$project}{gid});

=item C<admin_share_files>

Available files as returned by C<Schulkonsole::Sophomorix::create_file_list()>

=cut

$sk_session->set_var('admin_share_files',
	Schulkonsole::Sophomorix::create_file_list($admin_share_files));
};
if ($@) {
	if (    ref $@
	    and $@->{code} == Schulkonsole::Error::SophomorixError::WRAPPER_NO_SUCH_DIRECTORY) {
		$sk_session->set_status(
			$sk_session->d()->get(
				'Verzeichnis zum Bereitstellen nicht gefunden'), 1);
	} else {
		$sk_session->standard_error_handling($this_file, $@);
	}
}



my @projects;
foreach my $project (sort {
	$$projects{$a}{displayname} cmp $$projects{$b}{displayname} }
	keys %$projects) {
	push @projects, { gid => $project,
	                  name => $$projects{$project}{displayname},
	                };
}

=item C<projects>

Projects of the current user as an array of hashes with the keys

=over

=item C<gid>

GID of the project

=item C<name>

Name of the project

=back

=cut

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


=item C<isadmin>

Indicates that the current user is an administrator of the selected project

=cut

$sk_session->set_var('isadmin', 1);

=item C<project_gid>

The GID of the selected project

=cut

$sk_session->set_var('project_gid', $project);

=item C<project>

The name of the selected project

=cut

$sk_session->set_var('project', $$projects{$project}{displayname});



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


=back

=head2 Form fields

=over

=item C<handout>

Handout files

=back

