#!/usr/bin/perl -w
# $Id$
# This script (sophomorix-test-bunchofusers) 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 Sophomorix::SophomorixConfig;
use Sophomorix::SophomorixBase;
use Sophomorix::SophomorixPgLdap;
use Sophomorix::SophomorixTest;
use Test::More "no_plan";
Getopt::Long::Configure ("bundling");

use DBI;
use Net::LDAP;

my @arguments = @ARGV;

system("install -d /root/sophomorix-test");

my $dirname="";
my $linkname="";
my $mothergroup="";

my $file="";
my @teacher_files=();
my @userlist_to_check=();

# path to dumps of projects
my $truth_file_path="/usr/share/sophomorix-developer/projectfiles/";

# ===========================================================================
# Optionen verarbeiten
# ==========================================================================
my $help=0;
my $add=0;
my $login_users=0;
my $logout_users=0;
my $wsadd=0;
my $remove=0;
my $wsremove=0;
my $handout=0;
my $collect=0;
my $handoutcopy=0;
my $work=0;
my $projects=0;

# Parsen der Optionen
my $testopt=GetOptions(
                "help|h" => \$help,
                "add" => \$add,
                "login-users" => \$login_users,
                "logout-users" => \$logout_users,
                "wsadd" => \$wsadd,
                "work" => \$work,
                "handout" => \$handout,
                "collect" => \$collect,
                "handoutcopy" => \$handoutcopy,
                "remove|delete" => \$remove,
                "projects" => \$projects,
                "wsremove|wsdelete" => \$wsremove,
          );


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


# repair.directories einlesen ???
&get_alle_verzeichnis_rechte();

# fetch permission for all homes
&fetch_repairhome();


# --help
if ($help==1) {
   # Scriptname ermitteln
   my @list = split(/\//,$0);
   my $scriptname = pop @list;
   # Befehlbeschreibung
   print('
sophomorix-test-bunchofusers adds users, performs tests and removes users

Options
  -h  / --help
  -v  / --verbose
  -vv / --verbose --verbose
  -i  / --info
  
Adding users/workstations:
  --add
  --wsadd

Login users (students, teachers, workstations):
  --login-users

Logout users (students, teachers, workstations):
  --logout-users

Removing users/workstations:
  --remove 
  --wsremove

Performing tests
  --handout      (read only)
  --collect
  --handoutcopy  (copy to users home)

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

&check_connections();

if ($work==1){
    $handoutcopy=1;
    $collect=1;
    $handout=1;
}




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

# ACHTUNG:
#  -  Keine Sonderzeichen
#  -  Korrektes Datumsformat

# the schueler
my @userlist=(
  "12C;Thurau;Dietrich;12.10.1982;",
  "12C;Altig;Rudi;12.10.1981;",
  "12C;Bartali;Gino;14.12.1972;",
  "12C;Coppi;Fausto;12.01.1972;",
  "12C;Merckx;Eddy;12.01.1972;",
  "12C;Raas;Jan;12.01.1972;",
  "12C;DeVlaminck;Roger;12.01.1972;",
  "12C;Hinault;Bernard;12.01.1972;",
  "12C;Kuebler;Ferdi;12.01.1972;",
  "11A;Gillan;Ian;12.01.1972;",
  "11A;Blackmore;Ritchie;12.01.1978;",
  "11A;Glover;Roger;14.01.1972;",
  "11A;Lord;Jon;12.02.1972;",
  "11A;Paice;Ian;12.04.1974;",
  "11A;Plant;Robert;12.05.1974;",
  "11A;Page;Jimmy;12.08.1974;",
  "11A;Jones;JohnPaul;12.04.1976;",
  "11A;Bonham;John;02.04.1974;",
  "10C;Tempel;Wilhelm;02.04.1978;",
  "10C;Hale;Alan;02.05.1983;",
  "10C;Bopp;Thomas;01.06.1979;",
  "10C;Shoemaker;Carolyn;06.09.1989;",
  "10C;Levy;David;06.09.1989;",
  "10C;Hyakutake;Yuji;03.12.1974;",
  "10C;Ikeya;Kaoru;19.11.1974;",
  "10C;Seki;Tsutomu;28.10.1974;",
  "10C;Tschurjumow;Klim;28.10.1974;",
  "10C;Gerasimenko;Svetlana;28.10.1974;",
);

my @loginlist_students=("thuraudi", "altigru", "bartalgi", "coppifa", 
                        "merckxed", "raasja", "devlamro","hinaulbe",
                        "kueblefe","gillania","blackmri","gloverro",
                        "lordjo","paiceia","plantro","pageji",
                        "jonesjo","bonhamjo","tempelwi","haleal",
                        "boppth","shoemaca","levyda","hyakutyu",
                        "ikeyaka","sekits","tschurkl","gerasisv"  
                        );


# the lehrer
my @teacherlist=(
  "lehrer;Galilei;Galileo;12.10.1982;galli;",
  "lehrer;Bruno;Giordano;12.10.1981;bruno;",
  "lehrer;Kepler;Johannes;12.10.1970;hannes;",
  "lehrer;Kopernikus;Nikolaus;12.10.1976;niko;",
  "lehrer;Brahe;Tycho;12.10.1986;tycho;",
  "lehrer;Halley;Edmond;08.11.1986;hal;",
);

# the loginnames of the lehrer
my @loginlist_teachers=("tycho", "hannes", "bruno", "galli", "niko" );


my $teacher="";
my $login="";
my $today=`date +%d.%m.%Y`;
print "\nToday is $today";
chomp($today);
my $verbose=0;




###########################################################################
# Do I have to add some users?

if ($add==1 and not -e "/root/sophomorix-test/bunchofusers"){
    print '
###########################################################################
#                                                                         #
#                    ANLEGEN EINIGER SCHÜLER, LEHRER                      #
#                                                                         #
###########################################################################
';
    foreach my $user (@userlist){
       #my ($txt,$proto)=split(/==/, $user);
       &append_line("$user","${DevelConf::users_pfad}/schueler.txt");
    }

    print "Adding students ...\n";
    &run_command("sophomorix-check",$verbose);
    &run_command("sophomorix-add",$verbose);
    # 2x add bug in db ????????
    &run_command("sophomorix-add",$verbose);


    foreach my $teacher (@teacherlist){
       #my ($txt,$proto)=split(/==/, $teacher);
       &append_line("$teacher","${DevelConf::users_pfad}/lehrer.txt");
    }

    print "Adding teachers ...\n";
    &run_command("sophomorix-check",$verbose);
    &run_command("sophomorix-add",$verbose);


    foreach my $user (@userlist){
       my $login=&get_login_from_user($user);    
       # todo ??????
       #&check_account($login,"enabled");
    }


    foreach my $teacher (@teacherlist){
       my $login=&get_login_from_user($teacher);    
       # todo ??????
       #&check_account($login,"enabled");
    }


    # creating some projects
#system("sophomorix-project --update-from-file /usr/share/sophomorix-developer/projectfiles/starting-state.dump");
system("sophomorix-project --update-from-file ${truth_file_path}starting-state.dump");
#    system("sophomorix-project --create -p astro  --Admins tycho,niko --Members altigru,thuraudi,blackmri,pageji");
#    system("sophomorix-project --create -p chemie --Admins bruno,tycho --Members altigru,thuraudi,hannes,lordjo,gillania");
#    system("sophomorix-project --create -p micro  --Admins hannes --Members altigru,thuraudi,hinaulbe,raasja");

    # teacher tycho and bruno join a class 
    system("sophomorix-teacher --teacher bruno --add 11a");
    system("sophomorix-teacher --teacher tycho --add 11a");

    # creating 2 subclasses  in class 11a 
    system("sophomorix-subclass --split --noninteractive --class 11a  --AMembers gillania,blackmri,gloverro,paiceia,lordjo --BMembers plantro,pageji,jonesjo,bonhamjo");


    # Marking the added users
    system("touch /root/sophomorix-test/bunchofusers");
} elsif ($add==1 and -e "/root/sophomorix-test/bunchofusers"){
    print "The users are added already!\n";
} else {
    print "INFO: Not adding users!\n";
}




my $workstationhome="/home/workstations";
my $room1="134a";
my $room2="717b";

my @hostnames1=("pc0001","pc0002","pc0003","pc0004");
my @hostnames2=("Rechner1","Rechner2","Rechner3","Rechner4",
                "Rechner5","Rechner6","Rechner7","Rechner8");



if ($login_users==1){
    print '
###########################################################################
#                                                                         #
#             EINLOGGEN EXISTIERENDER USER/WORKSTATIONS                   #
#                                                                         #
###########################################################################
';
    my @list=(@loginlist_students,@loginlist_teachers,@hostnames1,@hostnames2);
    print "Loggin in all users:\n";
    foreach my $login (@list){
        my $ret=system("id $login > /dev/null");
        if ($ret==0){
            print "   * Logging in user $login (existing user)\n";
            system("sophomorix-bind --quick --login --host myhost --user $login --homedir /home/dummy > /dev/null");
        } else {
            print "   # User $login nonexisting\n";
        }
    }
}




if ($logout_users==1){
    print '
###########################################################################
#                                                                         #
#              AUSLOGGEN EXISTIERENDER USER/WORKSTATION                   #
#                                                                         #
###########################################################################
';
    my @list=(@loginlist_students,@loginlist_teachers,@hostnames1,@hostnames2);
    print "Loggin out all users:\n";
    foreach my $logout (@list){
        my $ret=system("id $logout > /dev/null");
        if ($ret==0){
            print "   * Logging out user $logout (existing user)\n";
            system("sophomorix-bind --quick --logout --host myhost --user $logout --homedir /home/dummy > /dev/null");
        } else {
            print "   # User $logout nonexisting\n";
        }
    }
}




if ($wsadd==1){
    print '
###########################################################################
#                                                                         #
#                    ANLEGEN EINIGER WORKSTATION-ACCOUNTS                 #
#                                                                         #
###########################################################################
';
   foreach my $hostname (@hostnames1){
      print "Adding $hostname to $room1\n";
      my $command=
         "sophomorix-useradd --unix-group $room1 --examaccount $hostname";
      system("$command");
      $command="sophomorix-useradd --computer $hostname\$";
      system("$command");
      &check_existence("$workstationhome/$room1/$hostname");
   }
   foreach my $hostname (@hostnames2){
      print "Adding $hostname to $room2\n";
      my $command=
         "sophomorix-useradd --unix-group $room2 --examaccount $hostname";
      system("$command");
      $command="sophomorix-useradd --computer $hostname\$";
      system("$command");
      &check_existence("$workstationhome/$room2/$hostname");
   }
} else {
    print "INFO: Not adding workstation users!\n";
}





if ($wsremove==1){
    print '
###########################################################################
#                                                                         #
#                    LÖSCHEN EINIGER WORKSTATION-ACCOUNTS                 #
#                                                                         #
###########################################################################
';
   foreach my $hostname (@hostnames1){
      print "Deleting $hostname\n";
      my $command="sophomorix-kill --killuser $hostname";
      #print "$command\n";
      system("$command");
      $command="sophomorix-kill --killuser $hostname\$";
      #print "$command\n";
      system("$command");
      &check_nonexistence("$workstationhome/$room1/$hostname");
   }
   foreach my $hostname (@hostnames2){
      print "Deleting $hostname\n";
      my $command="sophomorix-kill --killuser $hostname";
      system("$command");
      $command="sophomorix-kill --killuser $hostname\$";
      system("$command");
      &check_nonexistence("$workstationhome/$room2/$hostname");
   }
   system("sophomorix-groupdel -room $room1");
   system("sophomorix-groupdel -room $room2");
    &check_nonexistence($workstationhome/$room1);
    &check_nonexistence($workstationhome/$room2);
   # is remoed 
   #system("rmdir $workstationhome/$room1");
   #system("rmdir $workstationhome/$room2");
} else {
    print "INFO: Not removing workstation users!\n";
}




if ($projects==1){
    print '
###########################################################################
#                                                                         #
#                            CHECK PROJECTS                               # 
#                                                                         #
###########################################################################
';
    # starting state
    &update_from_file("starting-state.dump");
    &dump_an_diff_with("starting-state.dump");
    &check_membership("starting-state.dump");
    # state-1 by file
    &update_from_file("state-1.dump");
    &dump_an_diff_with("state-1.dump");
    &check_membership("state-1.dump");

}





if ($handout==1 and -e "/root/sophomorix-test/bunchofusers"){
    print '
###########################################################################
#                                                                         #
#            CHECK HANDOUT (Vorlagen bereitstellen: room)                 #
#                                                                         #
###########################################################################
';
   # DISTRIBUTE (Vorlagen)
   my $vorlagen_teacher="galli";
   my $vorlagen_gruppe="134a";
   my $type="room";

   # Working with these files
   @teacher_files=("testfile_1.txt","testfile_2.txt");
   @userlist_to_check=("pc0001",
                       "pc0002",
                       "pc0003",
                       "pc0004",
                      );
   &vorlagen_bereitstellen($vorlagen_teacher,
                           $vorlagen_gruppe,
                           $type);
    print '
###########################################################################
#                                                                         #
#            CHECK HANDOUT (Vorlagen bereitstellen: class)                #
#                                                                         #
###########################################################################
';
   # DISTRIBUTE (Vorlagen)
   $vorlagen_teacher="galli";
   $vorlagen_gruppe="11a";
   $type="adminclass";

   # Working with these files
   @teacher_files=("testfile_1.txt","testfile_2.txt");
   @userlist_to_check=("blackmri",
                       "bonhamjo",
                       "gillania",
                       "gloverro",
                       "jonesjo",
                       "lordjo",
                       "pageji",
                       "paiceia",
                       "plantro");
   &vorlagen_bereitstellen($vorlagen_teacher,
                           $vorlagen_gruppe,
                           $type);
    print '
###########################################################################
#                                                                         #
#            CHECK HANDOUT (Vorlagen bereitstellen: project)              #
#                                                                         #
###########################################################################
';
   # DISTRIBUTE (Vorlagen)
   $vorlagen_teacher="niko";
   $vorlagen_gruppe="p_astro";
   $type="project";

   # Working with these files
   @teacher_files=("testfile_3.txt","testfile_4.txt");
   @userlist_to_check=("tycho",
                       "niko",
                       "altigru",
                       "thuraudi",
                       "blackmri",
                       "pageji");
   $dirname="p_astro";
   $linkname="p_astro";
   &vorlagen_bereitstellen($vorlagen_teacher,
                           $vorlagen_gruppe,
                           $type);
    print '
###########################################################################
#                                                                         #
#            CHECK HANDOUT (Vorlagen bereitstellen: subclass)             #
#                                                                         #
###########################################################################
';
   # DISTRIBUTE (Vorlagen)
   $vorlagen_teacher="bruno";
   $vorlagen_gruppe="11a-A";
   $type="subclass";

   # Working with these files
   @teacher_files=("testfile_3.txt","testfile_4.txt");
   @userlist_to_check=("bruno",
                       "tycho",
                       "gillania",
                       "blackmri",
                       "gloverro",
                       "paiceia",
                       "lordjo");
   $dirname="11a-A";
   $linkname="11a-A";
   $mothergroup="11a";
   &vorlagen_bereitstellen($vorlagen_teacher,
                           $vorlagen_gruppe,
                           $type);
} elsif ($handout==1 and not -e "/root/sophomorix-test/bunchofusers"){
    print "The users must be added bofore checking tasks!\n";
} else {
    print "INFO: Not checking tasks!\n";
}





if ($collect==1 and -e "/root/sophomorix-test/bunchofusers"){
    print '
###########################################################################
#                                                                         #
# CHECK COLLECT (einsammeln: tycho,userliste,collectcopy,fromroom)        #
#                                                                         #
###########################################################################
';
   # COLLECT copy (Vorlagen) from project
   my $einsammeln_teacher="tycho";
   my $einsammeln_gruppe="";
   my $einsammeln_type="";
   my $einsammeln_option="collectcopy";
   my $einsammeln_exam="";

   # Working with these files
   @teacher_files=("testfile_4.txt","testfile_5.txt");
   @userlist_to_check=("altigru",
                       "blackmri",
                       "thuraudi",
                       "pc0003",
                       "pc0004",
                       "Rechner1",
                       "Rechner2",
                       "niko"
                      );
   my $userliste_collect="altigru,blackmri,thuraudi,pc0003,pc0004,Rechner1,Rechner2,niko";

   &dateien_einsammeln_userliste($einsammeln_teacher,
                            $userliste_collect,
                            $einsammeln_option,
                            "--fromroom"
                           );
    print '
###########################################################################
#                                                                         #
# CHECK COLLECT(einsammeln: tycho,userliste,collectcopy,fromproject=astro)#
#                                                                         #
###########################################################################
';
   # COLLECT copy (Vorlagen) from project
   $einsammeln_teacher="tycho";
   $einsammeln_gruppe="";
   $einsammeln_type="";
   $einsammeln_option="collectcopy";
   $einsammeln_exam="";

   # Working with these files
   @teacher_files=("testfile_4.txt","testfile_5.txt");
   @userlist_to_check=("altigru",
                       "blackmri",
                       "niko"
                      );
   $userliste_collect="altigru,blackmri,niko";

   &dateien_einsammeln_userliste($einsammeln_teacher,
                            $userliste_collect,
                            $einsammeln_option,
                            "--fromproject p_astro",
                            "p_astro"
                           );
    print '
###########################################################################
#                                                                         #
# CHECK COLLECT(einsammeln: tycho,userliste,collectcopy,fromproject=11a)  #
#                                                                         #
###########################################################################
';
   # COLLECT copy (Vorlagen) from project
   $einsammeln_teacher="niko";
   $einsammeln_gruppe="";
   $einsammeln_type="";
   $einsammeln_option="collectcopy";
   $einsammeln_exam="";

   # Working with these files
   @teacher_files=("testfile_3.txt","testfile_4.txt");
   @userlist_to_check=("gillania",
                       "blackmri",
                       "lordjo"
                      );
   $userliste_collect="gillania,blackmri,lordjo";

   &dateien_einsammeln_userliste($einsammeln_teacher,
                            $userliste_collect,
                            $einsammeln_option,
                            "--fromclass 11a",
                            "11a"
                           );
    print '
###########################################################################
#                                                                         #
#     CHECK COLLECT (Dat. einsammeln: tycho von userliste collect)        #
#                                                                         #
###########################################################################
';
   # COLLECT copy (Vorlagen) from project
   $einsammeln_teacher="tycho";
   $einsammeln_gruppe="134a";
   $einsammeln_type="room";
   $einsammeln_option="collect";
   $einsammeln_exam="--exam";

   # Working with these files
   @teacher_files=("testfile_4.txt","testfile_5.txt");
   @userlist_to_check=("altigru",
                       "blackmri",
                       "thuraudi",
                       "pc0003",
                       "pc0004",
                       "Rechner1",
                       "Rechner2",
                       "niko"
                      );
   $userliste_collect="altigru,blackmri,thuraudi,pc0003,pc0004,Rechner1,Rechner2,niko";

   &dateien_einsammeln_userliste($einsammeln_teacher,
                            $userliste_collect,
                            $einsammeln_option,
                            "--fromroom"
                           );
    print '
###########################################################################
#                                                                         #
#     CHECK COLLECT (Dat. einsammeln: tycho von room,exam collect)        #
#                                                                         #
###########################################################################
';
   # COLLECT copy (Vorlagen) from project
   $einsammeln_teacher="tycho";
   $einsammeln_gruppe="134a";
   $einsammeln_type="room";
   $einsammeln_option="collect";
   $einsammeln_exam="--exam";

   # Working with these files
   @teacher_files=("testfile_4.txt","testfile_5.txt");
   @userlist_to_check=("pc0001",
                       "pc0002",
                       "pc0003",
                       "pc0004");
   &dateien_einsammeln($einsammeln_teacher,
                       $einsammeln_gruppe,
                       $einsammeln_type,
                       $einsammeln_option,
                       $einsammeln_exam);
    print '
###########################################################################
#                                                                         #
#     CHECK COLLECT (Dat. einsammeln: tycho von room,exam collectcopy)    #
#                                                                         #
###########################################################################
';
   # COLLECT copy (Vorlagen) from project
   $einsammeln_teacher="tycho";
   $einsammeln_gruppe="134a";
   $einsammeln_type="room";
   $einsammeln_option="collectcopy";
   $einsammeln_exam="--exam";

   # Working with these files
   @teacher_files=("testfile_3.txt","testfile_4.txt");
   @userlist_to_check=("pc0001",
                       "pc0002",
                       "pc0003",
                       "pc0004");
   &dateien_einsammeln($einsammeln_teacher,
                       $einsammeln_gruppe,
                       $einsammeln_type,
                       $einsammeln_option,
                       $einsammeln_exam);
    print '
###########################################################################
#                                                                         #
#     CHECK COLLECT (Dateien einsammeln: tycho von room, collectcopy)     #
#                                                                         #
###########################################################################
';
   # COLLECT copy (Vorlagen) from project
   $einsammeln_teacher="tycho";
   $einsammeln_gruppe="134a";
   $einsammeln_type="room";
   $einsammeln_option="collectcopy";
   $einsammeln_exam="";

   # Working with these files
   @teacher_files=("testfile_1.txt","testfile_2.txt");
   @userlist_to_check=("altigru",
                       "blackmri",
                       "pageji",
                       "thuraudi");
   &dateien_einsammeln($einsammeln_teacher,
                       $einsammeln_gruppe,
                       $einsammeln_type,
                       $einsammeln_option,
                       $einsammeln_exam);
    print '
###########################################################################
#                                                                         #
#      CHECK COLLECT (Dateien einsammeln: tycho von room, collect)        #
#                                                                         #
###########################################################################
';
   # COLLECT copy (Vorlagen) from project
   $einsammeln_teacher="tycho";
   $einsammeln_gruppe="134a";
   $einsammeln_type="room";
   $einsammeln_option="collect";
   $einsammeln_exam="";

   # Working with these files
   @teacher_files=("testfile_1.txt","testfile_2.txt");
   @userlist_to_check=("altigru",
                       "blackmri",
                       "pageji",
                       "thuraudi");
   &dateien_einsammeln($einsammeln_teacher,
                       $einsammeln_gruppe,
                       $einsammeln_type,
                       $einsammeln_option,
                       $einsammeln_exam);
    print '
###########################################################################
#                                                                         #
#       CHECK COLLECT (Dateien einsammeln: niko von 12c, moven)           #
#                                                                         #
###########################################################################
';
   # COLLECT move (Vorlagen)
   $einsammeln_teacher="niko";
   $einsammeln_gruppe="12c";
   $einsammeln_type="adminclass";
   $einsammeln_option="collect";
   $einsammeln_exam="";

   # Working with these files
   @teacher_files=("testfile_1.txt","testfile_2.txt");
   @userlist_to_check=("altigru",
                       "bartalgi",
                       "coppifa",
                       "devlamro",
                       "hinaulbe",
                       "kueblefe",
                       "merckxed",
                       "raasja",
                       "thuraudi");
   &dateien_einsammeln($einsammeln_teacher,
                       $einsammeln_gruppe,
                       $einsammeln_type,
                       $einsammeln_option,
                       $einsammeln_exam);
    print '
###########################################################################
#                                                                         #
#    CHECK COLLECT (Dateien einsammeln: galli von 11a, collectcopy)       #
#                                                                         #
###########################################################################
';
   # COLLECT copy (Vorlagen)
   $einsammeln_teacher="galli";
   $einsammeln_gruppe="11a";
   $einsammeln_type="adminclass";
   $einsammeln_option="collectcopy";
   $einsammeln_exam="";

   # Working with these files
   @teacher_files=("testfile_1.txt","testfile_2.txt");
   @userlist_to_check=("blackmri",
                       "bonhamjo",
                       "gillania",
                       "gloverro",
                       "jonesjo",
                       "lordjo",
                       "pageji",
                       "paiceia",
                       "plantro");
   &dateien_einsammeln($einsammeln_teacher,
                       $einsammeln_gruppe,
                       $einsammeln_type,
                       $einsammeln_option,
                       $einsammeln_exam);
    print '
###########################################################################
#                                                                         #
# CHECK COLLECT (Dateien einsammeln: niko von project astro, collectcopy)#
#                                                                         #
###########################################################################
';
   # COLLECT copy (Vorlagen) from project
   $einsammeln_teacher="niko";
   $einsammeln_gruppe="p_astro";
   $einsammeln_type="project";
   $einsammeln_option="collectcopy";
   $einsammeln_exam="";

   # Working with these files
   @teacher_files=("testfile_1.txt","testfile_2.txt");
   @userlist_to_check=("altigru",
                       "blackmri",
                       "pageji",
                       "thuraudi");
   &dateien_einsammeln($einsammeln_teacher,
                       $einsammeln_gruppe,
                       $einsammeln_type,
                       $einsammeln_option,
                       $einsammeln_exam);

} elsif ($collect==1 and not -e "/root/sophomorix-test/bunchofusers"){
    print "The users must be added bofore checking collect!\n";
} else {
    print "INFO: Not checking collect!\n";
}




if ($handoutcopy==1 and -e "/root/sophomorix-test/bunchofusers"){
    print '
###########################################################################
#                                                                         #
#   CHECK HANDOUTCOPY (Dateien austeilen an userliste, aktueller raum)    #
#                                                                         #
###########################################################################
';
   # HANDOUT copy (Vorlagen) to room
   my $handout_teacher="niko";

   # Working with these files
   @teacher_files=("testfile_2.txt","testfile_3.txt");
   @userlist_to_check=("altigru",
                       "blackmri",
                       "pageji",
                       "thuraudi");
#   @userlist_to_check=("altigru",
#                       "blackmri",
#                       "pageji",
#                       "thuraudi",
#                       "pc0003",
#                       "pc0004",
#                       "Rechner1",
#                       "Rechner2");
   my $userliste="altigru,blackmri,pageji,thuraudi";
#   my $userliste="altigru,blackmri,pageji,thuraudi,pc0003,pc0004,Rechner1,Rechner2";


   &handoutcopy_files($handout_teacher,$userliste,"room","--fromroom","room");   



   $handout_teacher="galli";

   @teacher_files=("testfile_3.txt","testfile_4.txt");

   @userlist_to_check=("blackmri",
                       "pageji");

   $userliste="blackmri,pageji";


   &handoutcopy_files($handout_teacher,$userliste,"adminclass",
                      "--fromclass 11a","11a");   


   $handout_teacher="tycho";

   @teacher_files=("testfile_3.txt","testfile_4.txt");

   @userlist_to_check=("blackmri",
                       "pageji",
                       "altigru",
                       "niko");

   $userliste="blackmri,pageji,altigru,niko";


   &handoutcopy_files($handout_teacher,$userliste,"project",
                      "--fromproject p_astro","p_astro");   


} elsif ($handoutcopy==1 and not -e "/root/sophomorix-test/bunchofusers"){
    print "The users must be added bofore checking handout!\n";
} else {
    print "INFO: Not checking handout!\n";
}







###########################################################################
# Do I have to remove some users?


if ($remove==1 and -e "/root/sophomorix-test/bunchofusers"){
    print '
###########################################################################
#                                                                         #
#                ENTFERNEN ANGELEGTER SCHÜLER, LEHRER                     #
#                                                                         #
###########################################################################
';
    # removing projects
    system("sophomorix-project --kill -p p_astro");
    system("sophomorix-project --kill -p chemie");
    system("sophomorix-project --kill -p micro");



    # removing users
    foreach my $user (@userlist){
        &remove_line(
                "$user",
                "${DevelConf::users_pfad}/schueler.txt");
    }


    foreach my $teacher (@loginlist_teachers){
        &remove_line(
                ";$teacher",
                "${DevelConf::users_pfad}/lehrer.txt");
    }


    &run_command("sophomorix-check",$verbose);

    foreach my $user (@userlist){
        my $login=&get_login_from_user($user);    
        &update_user_db_entry($login,"TolerationDate=01.01.1970");
    }

    foreach my $teacher (@teacherlist){
        my $login=&get_login_from_user($teacher);    
        &update_user_db_entry($login,"TolerationDate=01.01.1970");
    }

    &run_command("sophomorix-check",$verbose);
    &run_command("sophomorix-move",$verbose);


    foreach my $user (@userlist){
        my $login=&get_login_from_user($user);    
        &update_user_db_entry($login,"DeactivationDate=01.01.1971");
    }

    foreach my $teacher (@teacherlist){
        my $login=&get_login_from_user($teacher);    
        &update_user_db_entry($login,"DeactivationDate=01.01.1971");
    }

    &run_command("sophomorix-check",$verbose);
# todo ?????
    &run_command("sophomorix-kill",$verbose);

    system("rm /root/sophomorix-test/bunchofusers");
} elsif($remove==1 and not -e "/root/sophomorix-test/bunchofusers") {
    print "The users are removed already!\n";

} else {
    print "INFO: Not removing users!\n";
}




&log_script_end(@arguments);




############################################################
# SUB
############################################################
sub dateien_einsammeln_userliste{
    my ($teacher,$users,$option,$add_option,$name) = @_;
    if (not defined $add_option){
	$add_option="";
    }
    if (not defined $name){
	$name="";
    }
    my ($type,$longname)=
       &Sophomorix::SophomorixPgLdap::pg_get_group_type($name);
    my @users = split(/,/,$users);
    my $command="";
    $command="sophomorix-user --reset-user $teacher";
    &run_command($command,$verbose);
    foreach my $user (@users){
       my @entry = getpwnam($user);
       my $homedir = "$entry[7]";
       $command="sophomorix-user --reset-user $user";
       &run_command($command,$verbose);
    } 

    foreach my $testfile (@teacher_files){
       foreach my $user (@userlist_to_check){
          my $create_this="";
          my @entry = getpwnam($user);
          my $homedir = "$entry[7]";
          $create_this="${homedir}/${Language::collect_dir}";
          $command="su --command='cp /usr/share/sophomorix-developer".
                   "/testfiles/${testfile} ${create_this}' root";
          &run_command($command,$verbose);
          $command="chown ${user}.root ${create_this}/${testfile}";
          &run_command($command,$verbose);
       }
    }

    $command="sophomorix-teacher --teacher $teacher --users $users $add_option --${option}";
    &run_command($command,$verbose);

    my $collect_dir="";
    my $collect_parent_dir;

    if ($add_option eq "--fromroom"){
        $collect_parent_dir="/home/teachers/${teacher}".
            "/${Language::collected_dir}/${Language::collected_string}".
            "${Language::current_room}";
    } else {
        $collect_parent_dir="/home/teachers/${teacher}".
            "/${Language::collected_dir}/".
            "${Language::collected_string}${longname}";
    }
    print "Collect parent dir is: $collect_parent_dir \n";
    opendir(COLL, $collect_parent_dir) 
         || die "can't opendir ",
                "$collect_parent_dir $!";
    while (defined(my $filename = readdir(COLL))) {
        #print "     Directory $filename found\n";
        if ($filename=~m/${Language::current_room}.*$/
            or
            $filename=~m/${longname}.*$/
            ){
          $collect_dir=$filename
	  }
    }
    closedir(COLL);

    print "Looking for collected data in $collect_dir \n";

    my @entry = getpwnam($teacher);
    my $homedir = "$entry[7]";
    foreach my $user (@userlist_to_check){
       my @entry_student = getpwnam($user);
       my $homedir_student = "$entry_student[7]";
       my $file;
       my $file_nonexist;
       foreach my $testfile (@teacher_files){
         if ($add_option eq "--fromroom"){
	    $file=$homedir."/${Language::collected_dir}/".
                           "${Language::collected_string}${Language::current_room}".
                           "/${collect_dir}/".
                           "${user}/".$testfile;
            $file_nonexist="${homedir_student}".
                        "/${Language::collect_dir}".
                        "/${testfile}"; 
         } else {
	    $file=$homedir."/${Language::collected_dir}/".
                           "${Language::collected_string}${longname}".
                           "/${collect_dir}/".
                           "${user}/".$testfile;
            $file_nonexist="${homedir_student}".
                        "/${Language::collect_dir}".
                        "/${testfile}"; 
         }

           &check_existence($file);
           if ($option eq "collect"){
               # data must be moved away
               &check_nonexistence($file_nonexist);
           } elsif ($option eq "collectcopy"){
               # data must still be there
               &check_existence($file_nonexist);
           } else {
	       print "Bad option $option";
               exit;
           }



       }
    }
}



sub dateien_einsammeln{
    my ($teacher,$group,$type,$option,$exam) = @_;
    my $command="";
    my $user_option="";
    my $users="";
    my ($group_type,$longname)=
       &Sophomorix::SophomorixPgLdap::pg_get_group_type($group);

    $command="sophomorix-user --reset-user $teacher";
    &run_command($command,$verbose);

    foreach my $user (@userlist_to_check){
       my @entry = getpwnam($user);
       my $homedir = "$entry[7]";
       $command="sophomorix-user --reset-user $user";
       &run_command($command,$verbose);

    }
    foreach my $testfile (@teacher_files){
       foreach my $user (@userlist_to_check){
           my $create_this="";
           my @entry = getpwnam($user);
           my $homedir = "$entry[7]";

           $create_this="${homedir}/${Language::collect_dir}";
           $command="su --command='cp /usr/share/sophomorix-developer".
                    "/testfiles/${testfile} ${create_this}' root";
           &run_command($command,$verbose);
           $command="chown ${user}.root ${create_this}/${testfile}";
           &run_command($command,$verbose);
       }
    }

    # collect files(?????? later do this as galli)
    if ($type eq "adminclass" or $type eq "project" or $type eq "subclass"){
        $command = "sophomorix-teacher --teacher".
                   " $teacher --${option} --${type} $group";
    } elsif ($type eq "room"){
        if ($exam eq ""){
            $user_option=join(",",@userlist_to_check);
            $user_option="--users ".$user_option;
        } elsif ($exam eq "--exam") {
            $user_option="";
        }
        $command="sophomorix-teacher --teacher $teacher ".
                 "--${option} --${type} $group $user_option $exam";
    }

    &run_command($command,$verbose);
    my $collect_dir="";
    my $collect_parent_dir="";
    if ($type eq "adminclass" or $type eq "project" or $type eq "subclass"){
       $collect_parent_dir="/home/teachers/${teacher}/".
           "${Language::collected_dir}/${Language::collected_string}${longname}";
    } elsif ($type eq "room" and $exam eq ""){
       $collect_parent_dir = "/home/teachers/${teacher}".
               "/${Language::collected_dir}/${Language::collected_string}".
               "${Language::current_room}";
    } elsif ($type eq "room" and $exam eq "--exam"){
       $collect_parent_dir = "/home/teachers/${teacher}".
               "/${Language::collected_dir}/".
               "${Language::collected_string}${Language::exam}";
    }

    print "Collect parent dir is: $collect_parent_dir \n";
    opendir(COLL, $collect_parent_dir) 
         || die "can't opendir ",
                "$collect_parent_dir $!";
    while (defined(my $filename = readdir(COLL))) {
        # print "     Directory $filename found\n";
        if ($filename=~m/${longname}.*$/ 
            or
            $filename=~m/${Language::current_room}.*$/ ){
          $collect_dir=$filename
	  }
    }
    closedir(COLL);
    
    print "Looking for collected data in $collect_dir \n";
    foreach my $user (@userlist_to_check){
        my @entry = getpwnam($user);
        my $homedir = "$entry[7]";
        foreach my $testfile (@teacher_files){
	   my $file_nonexist;

           if ($type eq "adminclass" or $type eq "project" or $type eq "subclass"){
               $file="/home/teachers/${teacher}/${Language::collected_dir}".
                     "/${Language::collected_string}${longname}/".
                     "${collect_dir}/${user}/${testfile}"; 
           } elsif ($type eq "room" and $exam eq ""){
               $file="/home/teachers/${teacher}/${Language::collected_dir}".
                     "/${Language::collected_string}${Language::current_room}".
                     "/${collect_dir}/${user}/${testfile}"; 
           } elsif ($type eq "room" and $exam eq "--exam"){
               $file="/home/teachers/${teacher}/${Language::collected_dir}".
                     "/${Language::collected_string}${Language::exam}/".
                     "${collect_dir}/${user}/${testfile}"; 
           }
           $file_nonexist="${homedir}".
                     "/${Language::collect_dir}".
                     "/${testfile}"; 

           &check_existence($file);
           if ($option eq "collect"){
               # data must be moved away
               &check_nonexistence($file_nonexist);
           } elsif ($option eq "collectcopy"){
               # data must still be there
               &check_existence($file_nonexist);
           } else {
	       print "Bad option $option";
               exit;
           }
	}
    }
}




sub vorlagen_bereitstellen{
    # howto:
    # class:   $linkname is $group
    #          $dirname is $group       
    # project: $linkname    # must be given before calling
    #          $dirname     # vorlagen_bereitstellen
    # subclass:$linkname    # must be given before calling
    #          $dirname     # vorlagen_bereitstellen
    my ($teacher,$group,$type) = @_;
    my $command="";
    my $file="";
    my $exam="";

    if ($type eq "project"){
       # $linkname (global should be given before calling this function) 
       # $dirname  (global should be given before calling this function)
       $dirname=${Language::handout_string}.$dirname; 
       # $mothergroup (global should be given before calling this function) 
    } elsif ($type eq "subclass"){
       # $linkname (global should be given before calling this function) 
       # $dirname  (global should be given before calling this function) 
       $dirname=${Language::handout_string}.$dirname; 
       # $mothergroup (global should be given before calling this function) 
    } elsif ($type eq "room"){
       $exam="--exam";
       $linkname=$group;  
       $dirname="${Language::handout_string}klassenarbeit";  
       $mothergroup=$group;
    } else {
       $linkname=$group;  
       $dirname="${Language::handout_string}$group";  
       $mothergroup=$group;

    }

    $command="sophomorix-user --reset-user $teacher";
    &run_command($command,$verbose);

    foreach my $user (@userlist_to_check){
        $command="sophomorix-user --reset-user $user";
        &run_command($command,$verbose);
    }


    # remove the teacher from this class
    if ($type eq "adminclass" or $type eq "subclass"){
        $command="sophomorix-teacher --teacher $teacher --remove $mothergroup";
        &run_command($command,$verbose);
    }

    # do this with add already
    # join the class 11a (?????? later do this as galli)
    if ($type eq "adminclass"){
       $command="sophomorix-teacher --teacher $teacher --add $group";
       print "$command \n";
       system($command);
    } elsif ($type eq "subclass"){
       $command="sophomorix-teacher --teacher $teacher --add $mothergroup";
       &run_command($command,$verbose);
    }

    # was directory created ?
    $file="/home/teachers/${teacher}/${Language::handout_dir}".
          "/${dirname}"; 
    ok(-e $file, "$file existiert");

    foreach my $testfile (@teacher_files){
        if ($type eq "room"){
            $command="su --command='cp /usr/share/sophomorix-developer/testfiles/${testfile} /home/teachers/${teacher}/${Language::handout_dir}/${Language::handout_string}${Language::exam}'/";
        } else {
            $command="su --command='cp /usr/share/sophomorix-developer/testfiles/${testfile} /home/teachers/${teacher}/${Language::handout_dir}/${dirname}'/";
        }
        &run_command($command,$verbose);
    }

    # distribute files(?????? later do this as galli)
    $command="sophomorix-teacher --teacher $teacher --handout --${type} $group $exam";
    &run_command($command,$verbose);

    # was file handed out ?
    foreach my $testfile (@teacher_files){
       foreach my $user (@userlist_to_check){
          # home ermitteln
          my @entry = getpwnam($user);
          my $homedir = "$entry[7]";


          $file="${homedir}/${Language::task_dir}/${Language::task_string}".
                "${linkname}/${teacher}/${testfile}"; 
          ok(-e $file, "$file existiert");
       }
    }
}





sub handoutcopy_files {
    my ($teacher,$users,$type,$add_options,$group) = @_;
    my @users = split(/,/,$users);
    my $command="";
    my $longname;
    if ($type eq "project"){
        ($longname) =
         &Sophomorix::SophomorixPgLdap::fetchinfo_from_project($group);
    } else {
	$longname=$group;
    }
    $command="sophomorix-user --reset-user $teacher";
    &run_command($command,$verbose);
    foreach my $user (@users){
       my @entry = getpwnam($user);
       my $homedir = "$entry[7]";
       $command="sophomorix-user --reset-user $user";
    &run_command($command,$verbose);
    } 

    foreach my $testfile (@teacher_files){
       if ($add_options eq "--fromroom"){
          $command="su --command='cp /usr/share/sophomorix-developer/testfiles/${testfile} /home/teachers/${teacher}/${Language::to_handoutcopy_dir}/${Language::to_handoutcopy_string}${Language::current_room}'";
          &run_command($command,$verbose);
       } else {

          $command="su --command='cp /usr/share/sophomorix-developer/testfiles/${testfile} /home/teachers/${teacher}/${Language::to_handoutcopy_dir}/${Language::to_handoutcopy_string}$longname'";
          &run_command($command,$verbose);
       }
    }

    $command="sophomorix-teacher --teacher $teacher --users $users $add_options --handoutcopy";
    &run_command($command,$verbose);
    foreach my $user (@userlist_to_check){
       foreach my $testfile (@teacher_files){
         my @entry = getpwnam($user);
         my $homedir = "$entry[7]";
         my $file="";
       if ($add_options eq "--fromroom"){
            $file="$homedir/${Language::handoutcopy_dir}/".
                  "${Language::handoutcopy_string}${Language::current_room}".
                  "/$testfile";
       } else {
            $file="$homedir/${Language::handoutcopy_dir}/".
                  "${Language::handoutcopy_string}${longname}/$testfile";
       }
         &check_existence($file);
       }
    }
}





sub get_login_from_user {
    my ($user) = @_;
    my $login="";
    my ($class,$last,$first,$birth)=split(/;/,$user);
    $class=~tr/A-Z/a-z/; # in Kleinbuchstaben umwandeln
    if ($class eq "lehrer"){
        $class="teachers",
    }
    #$last=~tr/A-Z/a-z/; # in Kleinbuchstaben umwandeln
    #$first=~tr/A-Z/a-z/; # in Kleinbuchstaben umwandeln

    $birth=&date_perl2pg($birth);

    # Fetch login of user
    $login = &fetch_login("surname='$last' 
                          AND firstname='$first'
                          AND birthday='$birth'",
                         );
    return $login;
}



sub dump_an_diff_with {
    my ($truth_file) = @_;
#    my $truth_file_path="/usr/share/sophomorix-developer/projectfiles/";
    my $truth_file_abs=$truth_file_path.$truth_file;
    my $sys_file="dump.sys";
    my $sys_path="/root/sophomorix-developer/projectdumps/";
    system("install -d $sys_path");
    my $truth=$sys_path."dump.truth";
    my $sys_file_abs=$sys_path.$sys_file;

    unlink $sys_file_abs;
    system("sophomorix-project --dump $sys_file_abs");
    my $replace= " -e 's/\.id=\[0-9\]\[0-9\]\[0-9\]/\.id=xxx/g'". 
                 " -e 's/\.creationdate.*/\.creationdate/g'". 
                 " -e '/^\#/d'"; # Kommentarzeilen löschen 

    system("cp $truth_file_abs $truth");
    system("sed $replace $truth > $truth.mod"); 
    system("sed $replace $sys_file_abs > $sys_file_abs.mod"); 
    my $diff_result=`diff $truth.mod $sys_file_abs.mod`;
#    my $diff_result=`diff $truth.mod $truth.mod`;
    &is($diff_result,"" , "Checking diff truth <> system");
}


sub check_membership {
    my ($truth_file) = @_;
    #my $truth_file_path="/usr/share/sophomorix-developer/projectfiles/";
    my $truth_file_abs=$truth_file_path.$truth_file;

    my @pro_list=();
    my %member_info=();
    my %member_info2=();
    # fetch project list
    open(PROS, "<$truth_file_abs");
    while(<PROS>) {
	if (/^\[(.*)\]/){
            push @pro_list, $1;
        }
    }
    close(PROS);

    # fetch membership information
    open(PROS, "<$truth_file_abs");
    while(<PROS>) {
	if (/^\# {0,3}(.*)\.expected_sec_users=(.*)/){
            #print "---$1---  ---$2---\n";
            my @member=split(/,/,$2);
            @member = sort @member;
            my $string =join(",",@member);
            foreach my $member (@member){
                $member_info{$1}{$member}="should be member";
                $member_info2{$1}="$string";
            }
        }
    }
    close(PROS);

    foreach my $project (@pro_list) {
        my @realmembers=&fetchusers_from_project($project);

        # check all real members if they are correct
        foreach my $real_mb (@realmembers){
            my $true=0;
            if (exists $member_info{$project}{$real_mb}){
                delete $member_info{$project}{$real_mb};
                $true=1;
            }   
            &is($true,1,
             "Checking if membership of $real_mb in $project is correct");
        } 

        # all whats left is bugs
        while (my ($user,$v) = each %{ $member_info{$project} }) {
            # dont check, throw error
            &is(0,1,"User $user must be a member, but is not");
        }
    }
}



sub update_from_file {
    my ($state_file) = @_;
    system("sophomorix-project --update-from-file ${truth_file_path}${state_file}");
    
}
