#!/usr/bin/perl -w
#     Hey, EMACS: -*- perl -*-
# $Id$
# This script (sophomorix-teacher) is maintained by Rüdiger Beck
# It is Free Software (License GPLv3)
# If you find errors, contact the author
# jeffbeck@web.de  or  jeffbeck@gmx.de


# Bibliotheken
use strict;
use Getopt::Long;
# use log names of perl variables, i.e. $UID
use English;
use Sophomorix::SophomorixConfig;
use Sophomorix::SophomorixAPI;
use DBI;
Getopt::Long::Configure ("bundling");
use Sophomorix::SophomorixBase qw( check_options 
                                   linie
                                   log_script_start
                                   log_script_end
                                   share_access
                                   handout
                                   handoutcopy
                                   collect
                                   get_alle_verzeichnis_rechte
                                   fetch_repairhome
                                   fetch_smb_conf
                                 );

use Sophomorix::SophomorixPgLdap qw(show_modulename
                                    fetch_my_adminclasses
                                    show_class_teacher_list
                                    show_teacher_class_list
                                   );

my @arguments = @ARGV;
@arguments = ("--skiplock", @arguments);
#foreach my $arg (@arguments){
#    print "  <$arg>  \n";
#}

############################################################
# Start
############################################################

$Conf::log_level=1;
my $help=0;
my $add="";
my $remove="";
my $teacher="";
my $handout=0;
my $handoutcopy=0;
my $collect=0;
my $collectcopy=0;
my $class="";
my $subclass="";
my $project="";
my $users="";
my $fromroom=0;
my $fromproject="";
my $fromclass="";
my $room="";
my $exam=0;
my $info=0;
my $show_classes=0;
my $show_teachers=0;
my $shares;
my $remove_classes_from_teachers=0;

my @users=();


# Parsen der Optionen
my $testopt=GetOptions(
           "verbose|v+" => \$Conf::log_level,
           "help|h" => \$help,
           "add=s" => \$add,
           "remove=s" => \$remove,
           "teacher|t=s" => \$teacher,
           "handout" => \$handout,
           "handoutcopy" => \$handoutcopy,
           "collect" => \$collect,
           "collectcopy" => \$collectcopy,
           "class|adminclass|c=s" => \$class,
           "subclass=s" => \$subclass,
           "project=s" => \$project,
           "fromproject=s" => \$fromproject,
           "fromclass=s" => \$fromclass,
           "fromroom|currentroom" => \$fromroom,
           "room=s" => \$room,
           "exam" => \$exam,
           "info|i" => \$info,
           "showclasses" => \$show_classes,
           "showteachers" => \$show_teachers,
           "remove-classes-from-teachers" => \$remove_classes_from_teachers,
           "shares!" => \$shares,
           "users=s" => \$users,
          );


# Prüfen, ob Optionen erkannt wurden
&check_options($testopt);


# repair.directories einlesen
&get_alle_verzeichnis_rechte();

# fetch permission for all homes
&fetch_repairhome();

# fetch permissions for creation of files 
&fetch_smb_conf();


my $UID_name=getpwuid($UID);
my $EUID_name=getpwuid($EUID);
my ($GID_name)=getgrgid($GID);
my ($EGID_name)=getgrgid($EGID);


if($Conf::log_level>=3){
    print "UID:  $UID ($UID_name)\n",
          "EUID: $EUID ($EUID_name)\n",
          "GID:  $GID ($GID_name)\n", 
          "EGID: $EGID ($EGID_name)\n\n";
}


# make calls including path not tainted
$ENV{'PATH'} = '/bin:/usr/bin';



# --help
if ($help==1) {
   # Scriptname ermitteln
   my @list = split(/\//,$0);
   my $scriptname = pop @list;
   # Befehlbeschreibung
   print "\n$scriptname manages your MyAdminClasses and distributes", 
         "collects and archives Data used during lessons or exams.\n";
   print('
Options
  -h  / --help
  -i -t teacher / --info --teacher teacher
  -v  / --verbose
  -vv / --verbose --verbose

Manage memberships:
  --add AdminClass
  --remove AdminClass
  --remove-classes-from-teachers

Show memberships
  --showclasses
  --showteachers

What to do:
  --handout      (bereitstellen)
  --handoutcopy  (austeilen)
  --collect      (einsammeln)
  --collectcopy  (Kopie einsammeln)

Select students/teachers to work with:
  --class class
  --subclass subclass
  --project project
  --users user1,user2,user3,...
  --room room

  --exam
  --fromroom/--currentroom (aktueller_raum)
  --fromproject project
  --fromclass class

Globally switch on/off shares:
  --shares --users user1,user2,...
  --noshares --users user1,user2,...
   

Options for the user root
  --teacher teacher

Please see the sophomorix-teacher(1) man pages for full documentation
');
   print "\n";
   exit;
}



if ($users ne ""){
    (@users) = split(/,/,$users);
}


if ($show_classes==1){
    &show_class_teacher_list();
    exit;
}



if ($show_teachers==1){
    &show_teacher_class_list();
    exit;
}



# get login name of the user that calls the script
my $login=getpwuid($UID);
if ($login eq "root"){
    # if caller is root
    if ($teacher ne ""){
       $login=$teacher;
    } elsif ($remove_classes_from_teachers==1) {
       # just move on
    } else {
       print "As root, you must specify a teacher with --teacher login \n";
       exit;
    }
}



############################################################
# Managing MyAdminClasses
############################################################


# show info if nothing has to be changed
if ($add eq "" and 
    $remove eq "" and
    $handout==0 and
    $handoutcopy==0 and
    $collect==0 and
    $collectcopy==0 and
    $remove_classes_from_teachers==0 and
    not defined $shares
   ){
    $info=1;
}



if (defined $shares and not @users){
    print "You must give users to switch shares on/off\n";
    exit;
}

############################################################
# Info
############################################################
# --info
# Display info and exit

if ($info==1 
    and $collect==0 
    and $collectcopy==0 
    and $handout==0 
    and $exam==0
    and $users eq ""){
   my @list=&fetch_my_adminclasses($login);
   if ($#list==-1){
      print "\nTeacher $login has no AdminClasses in his list\n";
      print "Add a class with:   --add classname\n";
   } else {
      print "AdminClasses of $login:\n";
      foreach my $item (@list){
         print "   $item \n";
      }
   }
   exit;
} elsif ($info==1 and $collect==1 and $handout==0){
    # collect-info
    # ????? todo
   exit;
} elsif ($info==1 and $collect==0 and $handout==1){
   # handout-info
    my $ha_basedir = "${DevelConf::homedir_teacher}/$login/${Language::task_dir}";
    my $handout_dir = ""; 

    if ($class ne ""){
       $handout_dir = "${ha_basedir}/$class"; 
       my @list=&fetch_my_adminclasses($login);
       my $seen=0;
       foreach my $item (@list){
	   if ($item eq $class){$seen=1}
       }
       if ($seen==1){
          print "\nINFO: I would hand out $handout_dir to class $class:\n";
          &linie();
          system("ls $handout_dir");
          print "\n";
       } else {
          print "$class is not in MyAdmiClasses (add a class with:  --add class)\n";
       }
    }
    if ($subclass ne ""){
       $handout_dir = "${ha_basedir}/$subclass"; 
       print "\nINFO: I would hand out $handout_dir to subclass $subclass:\n";
       &linie();
       system("ls $handout_dir");
       print "\n";
    }
    if ($project ne ""){
       $handout_dir = "${ha_basedir}/$project"; 
       print "\nINFO: I would hand out $handout_dir to project $project:\n";
       &linie();
       system("ls $handout_dir");
       print "\n";
    }
    exit;
}


&log_script_start(@arguments);


## --remove-classes-from-teachers
if ($remove_classes_from_teachers==1){
    my @teachers=&Sophomorix::SophomorixPgLdap::fetchusers_from_adminclass(${DevelConf::teacher});
    foreach my $teacher (@teachers){
        print "Working on $teacher:\n";
        my @classes=&fetch_my_adminclasses($teacher);
        if ($#classes==-1){ # empty list
            print "   * Nothing to do.\n";
            next;
        }
        foreach my $class (@classes){
            print "   * Removing $class\n";
            &remove_my_adminclass($teacher,$class);
        }
    }
    # Creating Mailing Aliases and Lists
    system("/usr/sbin/sophomorix-mail");
    &log_script_end(@arguments);
}



# --add class
if ($add ne ""){
   my $result=&add_my_adminclass($login,$add);
   $info=1;
   # Creating Mailing Aliases and Lists
   if ($result==1){
       system("/usr/sbin/sophomorix-mail");
   }
   &log_script_end(@arguments);
}




# --remove class
if ($remove ne ""){
   &remove_my_adminclass($login,$remove);
   $info=1;
   # Creating Mailing Aliases and Lists
   system("/usr/sbin/sophomorix-mail");
   &log_script_end(@arguments);
}






############################################################
# Handout
############################################################
# --handout
if ($handout==1 and ($class ne "" 
                  or $subclass ne "" 
                  or $project ne ""
                  or $room ne "")){
    my $group_type="";
    my $rsync="delete";
    print "Calling handout with rsync option $rsync\n";
    if ($class ne ""){
           &handout($login, $class,"adminclass",$rsync);
    }
    if ($subclass ne ""){
           &handout($login, $subclass,"subclass",$rsync);
    }
    if ($project ne ""){
           &handout($login, $project,"project",$rsync);
    }
    if ($room ne ""){
           &handout($login, $room,"room",$rsync);
    }
    &log_script_end(@arguments);
}


############################################################
# Handoutcopy
############################################################
# --handoutcopy
if ($handoutcopy==1 and (
                ($users ne "" and $fromroom==1)
             or ($users ne "" and $fromproject ne "")
             or ($users ne "" and $fromclass ne "")
                        )){
    my $type="";
    if ($fromroom==1){
	$type="current room";
    } elsif ($fromclass ne ""){
	$type="adminclass";
        $class=$fromclass;
    } elsif ($fromproject ne ""){
	$type="project";
        $class=$fromproject;
    }

    if ($users ne ""){
        print "Calling handoutcopy\n";
        &handoutcopy($login, $class,$type,"unused",$users);
    }
    &log_script_end(@arguments);
} elsif ($handoutcopy==1) {
    print "Cannot handoutcopy to class/subclass/project.\n";
    print "Use --users user1,user2,...\n";
}





############################################################
# Enable/Disable all shares
############################################################
# --share/--noshare
if (defined $shares){
    if ($shares==1){
	&share_access(1,@users);
    } else {
	&share_access(0,@users);
    }
}



############################################################
# Collect
############################################################

# --collect
if ($collect==1 and ($class ne "" 
                 or $subclass ne "" 
                 or $project ne ""
                 or $room ne ""
                 or ($users ne "" and $fromroom==1)
                 or ($users ne "" and $fromproject ne "")
                 or ($users ne "" and $fromclass ne "")
   )){
    my $group_type="";
    my $rsync="move";
    if ($class ne ""){
           &collect($login,$class,"adminclass",$rsync,$exam);
    }
    if ($subclass ne ""){
           &collect($login,$subclass,"subclass",$rsync,$exam);
    }
    if ($project ne ""){
           &collect($login,$project,"project",$rsync,$exam);
    }
    if ($room ne "" and $users ne ""){
        #  collect from userlist (current room)
        &collect($login,$room,"current room",$rsync,$exam,$users);
    }
    if ($room ne "" and $exam==1){
        #  collect from a room
        &collect($login,$room,"room",$rsync,$exam);
    }
    if ($users ne "" and $fromroom==1){
        #  collect from a userlist
        &collect($login,$room,"current room",$rsync,$exam,$users);
    }
    if ($users ne "" and $fromproject ne ""){
        #  collect from a userlist
        &collect($login,$fromproject,"project",$rsync,$exam,$users);
    }
    if ($users ne "" and $fromclass ne ""){
        #  collect from a userlist
        &collect($login,$fromclass,"adminclass",$rsync,$exam,$users);
    }
    &log_script_end(@arguments);
}


# --collectcopy
if ($collectcopy==1 and ($class ne "" 
                      or $subclass ne "" 
                      or $project ne ""
                      or $room ne ""
                      or ($users ne "" and $fromroom==1)
                      or ($users ne "" and $fromproject ne "")
                      or ($users ne "" and $fromclass ne "")
   )){

    my $group_type="";
    my $rsync="copy";
    if ($class ne ""){
           &collect($login,$class,"adminclass",$rsync,$exam);
    }
    if ($subclass ne ""){
           &collect($login,$subclass,"subclass",$rsync,$exam);
    }
    if ($project ne ""){
           &collect($login,$project,"project",$rsync,$exam);
    }
    if ($room ne "" and $users ne ""){
        #  collect from userlist (current room)   
        &collect($login,$room,"current room",$rsync,$exam,$users);
    }
    if ($room ne "" and $exam==1){
        #  collect from a room
        &collect($login,$room,"room",$rsync,$exam);
    }
    if ($users ne "" and $fromroom==1){
        #  collect from a userlist
        &collect($login,$room,"current room",$rsync,$exam,$users);
    }
    if ($users ne "" and $fromproject ne ""){
        #  collect from a userlist
        &collect($login,$fromproject,"project",$rsync,$exam,$users);
    }
    if ($users ne "" and $fromclass ne ""){
        #  collect from a userlist
        &collect($login,$fromclass,"adminclass",$rsync,$exam,$users);
    }
    &log_script_end(@arguments);
}


&log_script_end(@arguments);
