#!/usr/bin/perl -w
# $Id$
# This script (sophomorix-vampire) 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


# Einlesen der Konfigurationsdatei für Entwickler
#{ package DevelConf ; do "/etc/sophomorix/devel/user/sophomorix-devel.conf"}


# Bibliotheken
use strict;
use Quota;
use Getopt::Long;
Getopt::Long::Configure ("bundling");
use Sophomorix::SophomorixConfig;
use Sophomorix::SophomorixBase;
use Sophomorix::SophomorixAPI;

use Sophomorix::SophomorixPgLdap qw(show_modulename
                                    fetchdata_from_account
                                   );
use DBI;

my $server_key_location="";
my $command="";
my $fetch_files=0;
my $install_files=0;

my $help=0;
my $clear=0;
my $server="";
my $sync_user=0;
my $sync_homes=0;
my $sync_mail_data=0;
my $sync_mail=0;
my $sync_dirs=0;
my $sync_shares=0;
my $sync_teacher_share=0;
my $sync_prog_share=0;
my $sync_workstations=0;
my $configure_quota=0;
my $update_quota=0;
my $mlscripts=0;
my $myshn=0;
my $key=0;

my $delete=0;
my $delstr="";

my $loginname="";
my $classes="";
my $projects="";
my $student=0;
my @userlist=();
my $dir_old_files="/root/sophomorix-vampire/";
my $dir_config_files="/etc/sophomorix/vampire/";
my $old_ws_file=$dir_old_files."wimport_data";

my $old_version="2.x";


# Parsen der Optionen
my $testopt=GetOptions(
           "help|h" => \$help,
           "clear" => \$clear,
           "server=s" => \$server,
           "sync-users" => \$sync_user,
           "configure-quota" => \$configure_quota,
           "update-quota" => \$update_quota,
           "sync-homes" => \$sync_homes,
           "sync-mail-data" => \$sync_mail_data,
           "sync-mail" => \$sync_mail,
           "sync-dirs" => \$sync_dirs,
           "sync-shares" => \$sync_shares,
           "sync-teacher-share" => \$sync_teacher_share,
           "sync-prog-share" => \$sync_prog_share,
           "sync-workstations" => \$sync_workstations,
           "mlscripts" => \$mlscripts,
           "myshn" => \$myshn,
           "key" => \$key,
           "delete" => \$delete,
           "fetch-files" => \$fetch_files,
           "install-files" => \$install_files,
           "user|u=s" => \$loginname,
           "class|c=s" => \$classes,
           "project|projects|p=s" => \$classes,
           "student|students" => \$student,
          );

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

if ($sync_teacher_share==1){
    print "* Step 13:  synchronizing the teacher share\n";
    $sync_shares=1;
    $classes=${DevelConf::teacher};
}


if ($delete==1){
    $delstr="--delete";
}

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

# fetch permission for all homes
&fetch_repairhome();

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

# --help
if ($help==1) {
   # Scriptname ermitteln
   my @list = split(/\//,$0);
   my $scriptname = pop @list;
   # Befehlsbeschreibung
   print('
sophomorix-vampire sucks all data from an old linux-ml-server and uses it

PLEASE READ THE MANPAGE FOR INFORMATION

THIS IS OUTDATED

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


if ($server eq ""){
    # try to fetch server ip
    if (-e "${DevelConf::vampire_path}/server"){
       open (SERVER, "<${DevelConf::vampire_path}/server");
       while (<SERVER>){
	   chomp();
           $server=$_;
       }
       close(SERVER);
       print "* Using $server from ${DevelConf::vampire_path}/server as Server-IP\n";
    } else {
       # no IP available -> Error Message
       print "You must tell me which server I shall suck data from!\n";
       exit;
    }
} else {
    # save the server ip
    system("install -d ${DevelConf::vampire_path}");
    open (SERVER, ">${DevelConf::vampire_path}/server");
    print SERVER $server;
    close(SERVER);
}




############################################################
# Create userlist
############################################################

if ($loginname eq ""
    and $classes eq ""
    and $projects eq ""
    and $student==0){
      # without option: admins, teachers, students
      $student=1;
      @userlist=&create_userlist("",$DevelConf::teacher,0,
                                 "",0,$student,
                                 "",0,1,0);
} else {
    @userlist=&create_userlist($loginname,$classes,0,
                               $projects,0,$student,
                              "",0,0,0);
}


if ($#userlist+1==0){
     print "INFO: No valid users given\n";
     $help=1;
}





############################################################
# Step 1: put a key on the server to be sucked out
############################################################

my $key_dsa="/root/.ssh/vampire_key_dsa";

if ($key==1) {
    # generate key
    print "* Step 1:  copying a key to a server\n";
    print "Generating a key ...\n";
    system("/usr/bin/ssh-keygen -f ${key_dsa} -t dsa -N ''");
    # copy key
    print "Copying public key to other server...\n";
    $command="ssh-copy-id -i ${key_dsa}.pub root\@${server}";
    system("$command");
}


############################################################
# Step 2: fetch some files
############################################################


if ($clear==1) {
    print "Fetching configuration data once again.\n";
    system("rm -rf $dir_old_files");
    system("mkdir $dir_old_files");
    $fetch_files=1,
} elsif (not -e $dir_old_files){
    system("mkdir $dir_old_files");
}

if ($fetch_files==1){
    print "* Step 2:  fetching files to ${dir_old_files}\n";
    # reading the list of files to fetch from the old server
    my @files=&get_conf_lines("vampire_${old_version}_files");
    #foreach my $file (@files){
    #   print $file,"\n";
    #}
    foreach my $file (@files){
       $command="scp -i $key_dsa root\@${server}:$file $dir_old_files";
       print "\nFetching  $file ...\n";
       system("$command");
    }
    # rename some files
    system("mv $dir_old_files/schulinfo.txt $dir_old_files/class_db");
    system("mv $dir_old_files/user.protokoll $dir_old_files/user_db");
}



############################################################
# Step 3: install/patch some files
############################################################
if ($install_files==1){
    print "* Step 3:  install/patch configuration files from $dir_old_files\n";
    # schueler.txt
    print "   * copying  schueler.txt\n";
    system("cp ${dir_old_files}/schueler.txt ${DevelConf::users_pfad}/schueler.txt");
    # lehrer.txt
    print "   * copying/patching  lehrer.txt\n";
    # open infile and out file
    open (IN, "<${dir_old_files}/lehrer.txt");
    open (OUT, ">${DevelConf::users_pfad}/lehrer.txt");
    my $patched="";
    while (<IN>){
        chomp();
        if(/^\#/){
            $patched=$_;
        } else {
            my ($group,$last,$first,$birth,
                $login,$pass,$usertoken,$quota)= split(/;/);

            # replace kurz with usertoken
            if ($usertoken=~/kurz/){
                $usertoken=~s/kurz/usertoken/;
            }     

            # set standard quota for every teacher
            $quota="quota";

            $patched = $group.";".$last.";".$first.";".$birth.";".
                       $login.";".$pass.";".$usertoken.";".$quota.";";

        }
        #print $patched."\n";
	print OUT $patched."\n";
    }
    close(IN);
    close(OUT);

    # extraschueler.txt
    print "   * copying/patching  extraschueler.txt\n";
    system("cp ${DevelConf::config_template_pfad}/extraschueler.txt ${DevelConf::users_pfad}/extraschueler.txt");
    system(" echo '###\n### Lines from here are entrys from an update of $server with sophomorix-vampire\n###' >> ${DevelConf::users_pfad}/extraschueler.txt");
    system("cat ${dir_old_files}/extraschueler.txt >> ${DevelConf::users_pfad}/extraschueler.txt");
    # extrakurse.txt
    print "   * copying/patching  extrakurse.txt\n";
    system("cp ${DevelConf::config_template_pfad}/extrakurse.txt ${DevelConf::users_pfad}/extrakurse.txt");
    system(" echo '###\n### Lines from here are entrys from an update of $server with sophomorix-vampire\n###' >> ${DevelConf::users_pfad}/extrakurse.txt");
    system("cat ${dir_old_files}/extrakurse.txt >> ${DevelConf::users_pfad}/extrakurse.txt");
 

    # workstations
    print "   * copying/patching  workstations (wimport_data)\n";
    my $second_octett;
    my $max;
    my $internmask_debconf=
         &get_debconf_value("linuxmuster-base", "internmask",0);

    my $internsubrange_debconf=
         &get_debconf_value("linuxmuster-base", "internsubrange",0);
    # process debconf data
    if ($internsubrange_debconf ne 0){
        # from debconf
	($second_octett,$max)=split(/-/,$internsubrange_debconf);    
    }

    my %ip_map_second_octett=( "16" => "17",
                               "32" => "33",
                               "48" => "49",
                               "64" => "65",
                               "80" => "81",
                               "96" => "97",
                               "112" => "113",
                               "128" => "129",
                               "144" => "145",
                               "160" => "161",
                               "176" => "177",
                               "192" => "193",
                               "208" => "209",
                               "224" => "225",
                               "240" => "241");


    my $second_octett_client=$ip_map_second_octett{$second_octett};

    print "      * Second Octett of server IP from debconf             : $second_octett \n";
    print "      * Second Octett of IP for clients                     : $second_octett_client \n";
    print "      * Internal Netmask of server from debconf             : $internmask_debconf \n";

    # open infile and out file
    open (IN, "<${dir_old_files}/wimport_data");
#    open (OUT, ">/etc/linuxmuster/wimport_data_patched");
    open (OUT, ">/var/lib/rembo/files/global/wimport_data");
    my $patched_ws="";
    while (<IN>){
        chomp();

        if(/^\#/ 
           or $_ eq ""){
            $patched_ws=$_;
        } else {
            my ($room,$host,$hwk,$mac,$ip,$netmask,
                $part1,$part2,$part3,$part4,$pxe,$type)= split(/;/);

	    if (not defined $type){
                $type="";
            }

            if ($pxe eq "20"){
                $pxe="22";
            }

            my ($oct1,$oct2,$oct3,$oct4)=split(/\./,$ip);
            $oct1="10";
	    $oct2=$second_octett_client;
            $ip=join(".",$oct1,$oct2,$oct3,$oct4);

            $netmask=$internmask_debconf;

            $type="";

            $patched_ws = $room.";".$host.";".$hwk.";".$mac.";".$ip.";".$netmask.";".
		$part1.";".$part2.";".$part3.";".$part4.";".$pxe.";".$type.";";
            #print $patched_ws."\n";

        }
	print OUT $patched_ws."\n";
    }
    close(IN);
    close(OUT);

    # pxe 20 -> 22 ?
    # netmask anpassen
    # ip anpassen

}



############################################################
# Step 4: sync some dirs
############################################################


if ($sync_dirs==1){
    my @dirs=&get_conf_lines("vampire_${old_version}_dirs");
    #foreach my $dirline (@dirs){
    #   print $dirline,"\n";
    #}
    print "* Step 4:  synchronizing other dirs\n";
    &rsync_dirs(@dirs);
}



############################################################
# Step 5: sync the users
############################################################
if ($sync_user==1){
   print "* Step 5:  synchronizing users\n";
   system("sophomorix-check --no-auto-teach-in --get-info-from-old-files ${dir_old_files}");
   if ($classes ne ""){
       my $command="sophomorix-add -c $classes";
       print "\nCalling: $command \n\n";
       system("$command");
   } elsif ($loginname ne ""){
       my $command="sophomorix-add -u $loginname";
       print "\nCalling: $command \n\n";
       system("$command");
   } else {
       # alles
       my $command="sophomorix-add";
       print "\nCalling: $command \n\n";
       system("$command");
   }
   system("sophomorix-move");
}



############################################################
# Step 6: configure quota
############################################################
    my %quota_map=();
    my %new_quota_teacher=();
    my %new_quota_classes=();

    my $mailquota_map=-1;  
    my $new_mailquota_teacher=-1;
    my $new_mailquota_classes=-1;

if ($configure_quota==1){
    print "* Step 6:  configure quota\n";
    my $quota_config_file = "${dir_config_files}"."quota.config";
    if (-e "$quota_config_file"){
        print "READING $quota_config_file\n";
        { package Settings; do "$quota_config_file"}
    } else {
        print "ERROR: $quota_config_file not found \n";
        exit;
    }

    # map variables in package Settings to global variables in this file
    # avoid warnings
    my %tmp=%Settings::quota_map;
    %tmp=%Settings::new_quota_teacher;
    %tmp=%Settings::new_quota_classes;
    my $tmp=$Settings::mailquota_map;
    $tmp=$Settings::new_mailquota_teacher;
    $tmp=$Settings::new_mailquota_classes;

    %quota_map=%Settings::quota_map;
    %new_quota_teacher=%Settings::new_quota_teacher;
    %new_quota_classes=%Settings::new_quota_classes;
    $mailquota_map=$Settings::mailquota_map;
    $new_mailquota_teacher=$Settings::new_mailquota_teacher;
    $new_mailquota_classes=$Settings::new_mailquota_classes;

    # teacher.txt
    print "   * copying/patching lehrer.txt\n";
    open (IN, "<${dir_old_files}/lehrer.txt");
    open (OUT, ">${DevelConf::users_pfad}/lehrer.txt");
    my $patched_lq="";
    while (<IN>){
        chomp();
        if(/^\#/){
            $patched_lq=$_;
        } else {
            my ($group,$last,$first,$birth,
                $login,$pass,$usertoken,$quota,$mailquota)= split(/;/);

            # replace kurz with usertoken
            if ($usertoken=~/kurz/){
                $usertoken=~s/kurz/usertoken/;
            }     

            # remove whitespace
            $quota=~s/ //g;

            if ($quota=~/quota/){
               # do nthing
            } else {
               ($quota,$mailquota)=&configure_quota($quota,$mailquota,"teacher"); 
            }    

            $patched_lq = $group.";".$last.";".$first.";".$birth.";".
                       $login.";".$pass.";".$usertoken.";".$quota.";".$mailquota.";";
        }
	print OUT $patched_lq."\n";
    }
    close(IN);
    close(OUT);

    # info from class_db (schulinfo.txt)
    my $class_command="";
    print "   * scheduling the following commands:\n";
    open (CLASS, "<${dir_old_files}/class_db");
    open (COMMANDS, ">${dir_config_files}quota.commands");
    while (<CLASS>){
        chomp();
        s/^ //g; # Leerzeichen am Zeilenangfang entfernen

        if(/^\#/){
            # Comented line
            next;
        } elsif ($_ eq "") {
            # empty line
            next;
        } else {
            my $mailquota="";
            my ($class,$abt,$type,$m,$quota)= split(/;/);

            # remove whitespace
            $quota=~s/ //g;

            if ($quota=~/quota/){
               # do nothing
            } else {
               ($quota,$mailquota)=&configure_quota($quota,$mailquota,"classes"); 
               $class_command="sophomorix-class --class $class --quota $quota --mailquota $mailquota";
               print "     * $class_command\n";
               print COMMANDS "$class_command\n";
            }    
        }
    }
    close(CLASS);
    close(COMMANDS);
}


############################################################
# Step 7: update quota
############################################################
if ($update_quota==1){
    print "* Step 7:  update quota in the system\n";
    system("sophomorix-check");
    chmod 755, "${dir_config_files}quota.commands";
    if (-e "${dir_config_files}quota.commands"){
        system("${dir_config_files}quota.commands");
    }
    system("sophomorix-quota");
}



############################################################
# Step 8: synchronize the user homes
############################################################
if ($sync_homes==1){
   print "* Step 8:  synchronizing user homes\n";
   &print_list_column(6,"Userlist for synchronising \$HOME",@userlist);
   # do this for all users
   foreach my $user (@userlist){
     my $command="";

     # map user names
     my $old_user;
     if ($user eq "administrator"){
	 $old_user="admin";
     } else {
         $old_user=$user;
     }

     my $old_home = &fetch_old_home($old_user);
     my $new_home = &fetch_new_home($user);
     my ($group) = &Sophomorix::SophomorixPgLdap::pg_get_group_list($user);

     # do nothing when user did not exist on old system
     if ($old_home eq ""){
         print "Home of $old_user not found on old server, skipping ...\n";
         next;
     }

     # windows
     system("mkdir -p $new_home/${Language::user_attic}/windows");
     # linux
     system("mkdir -p $new_home/${Language::user_attic}/linux");

     {
     # windows
     my $source="${old_home}windows";
     my $target="${new_home}${Language::user_attic}";
     &titel("Synchronizig home of user $user (windows):");
     print "   $source \n     --> $target\n";
     $command="/usr/bin/rsync -e \"ssh -i $key_dsa\" -av $delstr root\@${server}:$source $target";
     print "$command\n";

     system($command); 

     # permissions and owner
     my ($unused_path,$dir_perm,$file_perm,
           $owner,$gowner)=&show_smb_conf_umask("homes");
     # owner,gowner are empty
     $owner=$user;
     $gowner=$group;
     &chmod_chown_dir("$new_home/${Language::user_attic}/windows",
                      $dir_perm,$file_perm,
                      $owner,$gowner);

     # linux
     my $lin_source="$old_home";
     my $lin_exclude="windows/";
     my $lin_target="${new_home}${Language::user_attic}/linux";

     print "   $lin_source \n     --> $lin_target\n";
     $command="/usr/bin/rsync -e \"ssh -i $key_dsa\" -av $delstr --exclude $lin_exclude root\@${server}:$lin_source $lin_target";
     print "$command\n";
     system($command); 
     &chmod_chown_dir("$new_home/${Language::user_attic}/linux",
                      $dir_perm,$file_perm,
                      $owner,$gowner);
    }

    # repair directories
    # needed to correct permissions owner www-run becomes www-data, ...
   }
}




############################################################
# Step 9: synchronize mbox maildata and .forward
############################################################
if ($sync_mail_data==1){
   print "* Step 9:  synchronizing mailbox maildata and .forward\n";
   &print_list_column(6,"Userlist for synchronising mailbox maildata and .forward",@userlist);
   # do this for all users
   foreach my $user (@userlist){
     my $command="";
     my $old_home = &fetch_old_home($user);
     my $new_home = &fetch_new_home($user);
     my ($group) = &Sophomorix::SophomorixPgLdap::pg_get_group_list($user);

     # mail mbox 2.x only
     system("mkdir -p $new_home/${Language::user_attic}/mail");
     # different 2.x and 3.0 ?????

     {
     # mail    
     my $mail_source="/var/spool/mail/${user}";
     my $mail_target="${new_home}${Language::user_attic}/mail/${user}";
     #system("scp -i $key_dsa root\@${server}:${mail_source} $mail_target");
     $command="/usr/bin/rsync -e \"ssh -i $key_dsa\" -av $delstr root\@${server}:$mail_source $mail_target";
     print "$command\n";
     system($command); 
     system("chown ${user}:${group} $new_home/${Language::user_attic}/mail");
     system("chmod 700 $new_home/${Language::user_attic}/mail");
     system("chown ${user}:${group} $mail_target");

     # copy .forward
     $command="scp -i $key_dsa root\@${server}:${old_home}.forward $new_home";
     print "$command\n";
     system($command); 
     if (-e "${new_home}.forward"){
         system("chown ${user}:${group} ${new_home}.forward");
     }
     }
   }
}








############################################################
# Step 10: read old mail into cyrus
############################################################
if ($sync_mail==1){
   print "* Step 10:  loading mail into cyrus\n";
   &print_list_column(6,"Userlist for loading mail into cyrus",@userlist);

   my $servername_debconf=
       &get_debconf_value("linuxmuster-base", "servername",0);
   my $domainname_debconf=
      &get_debconf_value("linuxmuster-base", "domainname",0);
   my $host=$servername_debconf.".".$domainname_debconf;


   # do this for all users
   foreach my $user (@userlist){
     my $command="";
     #my $new_home = &fetch_new_home($user);
     my ($new_home,$type,$gecos,$group,$uidnumber,$sambahomepath,
         $first_passwd) = &fetchdata_from_account($user);


     # upgrade from 2.x
     my $mailsync_dir=$new_home."/".${Language::user_attic}."/"."mailsync/";
     system("mkdir -p $mailsync_dir");
     my $mailsync_dotfile=$mailsync_dir.".mailsync";

     my $mailbox_file=$new_home."/".${Language::user_attic}."/".
                      "mail/".${user};

     if (not -e "$mailbox_file"){
	 print "User $user has no mailbox-file $mailbox_file\n";
	 print "Skipping user $user ...\n";
         next;
     }  

     print "Mailsync: $mailsync_dir\n";
     print "Mailbox: $mailbox_file\n";

     my $replace= " -e 's/\@\@user\@\@/${user}/g'". 
          " -e 's/\@\@user_attic\@\@/${Language::user_attic}/g'". 
          " -e 's/\@\@user_passwd\@\@/${first_passwd}/g'". 
          " -e 's/\@\@servername\@\@/${host}/g'"; 

     # 1) create config file for mailsync INBOX
     my $mailsync_template="/etc/sophomorix/vampire/user.mailsync";
     system("sed $replace ${mailsync_template} > ${mailsync_dotfile}"); 
     system("chown ${user}:${group} $mailsync_dir");

     # load mailbox file with this config
     $command="HOME=$new_home mailsync -f $mailsync_dotfile -m migrate";
     print "$command\n";
     system("$command");


     # 2) create config file for mailsync Folders
     $mailsync_dotfile=$mailsync_dir.".mailsync.folder";
     $mailsync_template="/etc/sophomorix/vampire/user.mailsync.folder";
     system("sed $replace ${mailsync_template} > ${mailsync_dotfile}"); 
     system("chown ${user}:${group} $mailsync_dir");

     # load mailbox file with this config
     $command="HOME=$new_home mailsync -f $mailsync_dotfile -m migrate";
     print "$command\n";
     system("$command");
   }
}





# what about horde database content?


############################################################
# Step 11: sync/add the workstations
############################################################

# run import_workstations
if ($sync_workstations==1){
   print "* Step 11:  importing the workstations\n";
   system("/usr/sbin/import_workstations");
}




############################################################
# Step 12: synchronize the shares
############################################################
if ($sync_shares==1){
    my @classes=();
    if ($classes eq ""){
        @classes=&Sophomorix::SophomorixPgLdap::fetchadminclasses_from_school("showhidden");
    } else {
        @classes=split(/,/,$classes);
    }

    my %old_id_old_group=();
    open(OLDGROUP, "${dir_old_files}group");
    while(<OLDGROUP>) {
	my ($name,$empty,$gid)=split(/:/);
        $old_id_old_group{$name}=$gid;
    }
    close(OLDGROUP);
    #while(my ($key, $value) = each(%old_id_old_group)) {
    #    # do something with $key and $value
    #    print "$key    $value \n";
    #}

    # create old_id new_group hash
    my %new_group_old_id=();
    # add teacher
    $new_group_old_id{$DevelConf::teacher}=$old_id_old_group{"lehrer"};
    my @groups=&Sophomorix::SophomorixPgLdap::fetchadminclasses_from_school("showhidden");
    foreach my $group (@groups){
        my $old_group="k".$group;
        my $old_id;
        if (defined $old_id_old_group{$old_group}){
            $old_id=$old_id_old_group{$old_group};
        } else {
            $old_id=0;
        }
        #print "New Group: $group Old Group: $old_group\n";
        #print "   Old id of $group  $old_id \n";
        $new_group_old_id{$group}="$old_id"; 
    }

    print "* Step 12:  synchronizing the student shares\n";
    #my $group="m3kb2t";
    # do this for all groups
    foreach my $group (@classes){
       # in 3.x no k before class ???
       my $old_share;
       my $new_share;
       if ( $group eq ${DevelConf::teacher} ){
           $old_share="/home/tausch/lehrer/*";
           $new_share="/home/share/teachers/";
       } else {
           $old_share="/home/tausch/klassen/k$group/*";
           $new_share="/home/share/classes/$group/";
       }
       my $command="/usr/bin/rsync -e \"ssh -i $key_dsa\" -avg $delstr root\@${server}:$old_share $new_share";
       print "$command \n";
       system($command);
       $command="chown -R :${group} ${new_share}";
       print "$command \n";
       system($command);

       # fix groupowner
#       my @grouplist=(${DevelConf::teacher},$group);
#       print "\nFixing groupowner\n";
#       foreach my $group_to_check (@grouplist){
#           if (defined $new_group_old_id{$group_to_check}){
#               $command="find $new_share -group ".
#                        "$new_group_old_id{$group_to_check}".
#                        " -print0 | xargs -0 chown :${group_to_check}".
#                        " $new_share";
#               print "\n$command\n";
#               system("$command");
#           } else {
#               print "WARNING: Could not find old id of $group_to_check \n";
#           }
#       }
    }
}







############################################################
# synchronize the school share
############################################################


############################################################
# rsync dirs im /etc/sophomorix/vampire/vampire_x.x_dirs
############################################################


############################################################
# mlscripts
############################################################

if ($mlscripts==1){
    print "* Step 14:  mlscripts stuff (rembo interface)\n";

    # fetching rembo.key
    my $old_rembo_key="/usr/local/rembo/rembo.key";
    my $new_rembo_key="/usr/share/rembo/rembo.key";
    my $rembo_key_command="scp -i $key_dsa root\@${server}:$old_rembo_key $new_rembo_key";
    
    system "$rembo_key_command";

    # copying mac files
    my $old_hosts="/usr/local/rembo/files/global/hosts";
    my $new_hosts="/var/lib/rembo/files/global/hosts";
    my $rsync_command="/usr/bin/rsync -e \"ssh -i $key_dsa\" -av $delstr --exclude '.*' root\@${server}:$old_hosts/ $new_hosts/";

    print "\n$rsync_command\n\n";
    system("$rsync_command");


    # copying remboinit.rbc
    my $old_ml_dir="/usr/local/rembo/files/global/groups";  
    my $new_ml_tmp_dir=$dir_old_files."mlscripts";  
    my $new_ml_dir="/var/lib/rembo/files/global/groups";  

    my $filename="remboinit.rbc";

    system("mkdir -p $new_ml_dir");
    system("mkdir -p $new_ml_tmp_dir");

    my $replace= " -e 's/\\/mlscripten\\//\\/mlscripts\\//g'"; 

    my @hw=&fetch_hw_classes();
    foreach my $hwc (@hw){
        print "Working on Hardware class $hwc \n";

        my $old_dir=$old_ml_dir."/".$hwc;
        my $new_dir_tmp=$new_ml_tmp_dir."/".$hwc;        
        my $new_dir=$new_ml_dir."/".$hwc;        

        system("mkdir -p $new_dir_tmp");
        my $command="scp -i $key_dsa root\@${server}:$old_dir/$filename $new_dir_tmp/$filename";
	# print "$command \n";
        system($command);

        if (-e "${new_dir_tmp}/${filename}"){
            my $command_sed=
               "sed $replace $new_dir_tmp/$filename > $new_dir/$filename"; 
	    # print "$command_sed\n";

            # modify files and put them into place
            system("mkdir -p $new_dir");
            system($command_sed);
        }
    }
}




############################################################
# myshn
############################################################

if ($myshn==1){
    print "* Step 14:  myshn stuff (rembo interface)\n";

    # fetching rembo.key
    my $old_rembo_key="/usr/local/rembo/rembo.key";
    my $new_rembo_key="/usr/share/rembo/rembo.key";
    my $rembo_key_command="scp -i $key_dsa root\@${server}:$old_rembo_key $new_rembo_key";
    
    system "$rembo_key_command";

    # fetching myshn.key
    my $old_myshn_key="/usr/local/rembo/files/global/myshn/myshn*.key";
    my $new_myshn_key="/var/lib/myshn";
    my $myshn_key_command="scp -i $key_dsa root\@${server}:$old_myshn_key $new_myshn_key";
    
    system "$rembo_key_command";

    # copying mac files
    #my $old_hosts="/usr/local/rembo/files/global/hosts";
    #my $new_hosts="/var/lib/rembo/files/global/hosts";
    #my $rsync_command="/usr/bin/rsync -e \"ssh -i $key_dsa\" -av $delstr --exclude '.*' root\@${server}:$old_hosts/ $new_hosts/";

    #print "\n$rsync_command\n\n";
    #system("$rsync_command");


    # copying config
    my $old_ml_dir="/usr/local/rembo/files/global/myshn/groups";  
    my $new_ml_tmp_dir=$dir_old_files."myshn";  
    my $new_ml_dir="/var/lib/myshn/groups";  

    my $filename="config";

    system("mkdir -p $new_ml_dir");
    system("mkdir -p $new_ml_tmp_dir");

    # patch config files
    my $replace= " -e 's/NoSIDPatch/\#NoSIDPatch/g'"; 
    #my $replace= ""; 

    my @hw=&fetch_hw_classes();
    foreach my $hwc (@hw){
        print "Working on Hardware class $hwc \n";

        # add Hardware Class to paths
        my $old_dir=$old_ml_dir."/".$hwc;
        my $new_dir_tmp=$new_ml_tmp_dir."/".$hwc;        
        my $new_dir=$new_ml_dir."/".$hwc;        


        system("mkdir -p $new_dir_tmp");

        my $command="scp -i $key_dsa root\@${server}:$old_dir/$filename $new_dir_tmp/$filename";
	# print "$command \n";
        system($command);

        if (-e "${new_dir_tmp}/${filename}"){
            my $command_sed=
               "sed $replace $new_dir_tmp/$filename > $new_dir/$filename"; 
	    # print "$command_sed\n";

            # modify files and put them into place
            system("mkdir -p $new_dir");
            system($command_sed);
            #system("cp $new_dir_tmp/$filename $new_dir/$filename");
        }
    }
}




############################################################
# program share
############################################################

if ($sync_prog_share==1){
    print "* Step 15:  sync the program share \n";
    my $old_share="/usr/local/samba/progs";
    my $new_share="/home/samba";
    $command="/usr/bin/rsync -e \"ssh -i $key_dsa\" -av $delstr root\@${server}:$old_share $new_share";
  
     print "$command\n";
     system($command); 

     # adjust owner
     $command="chown -R pgmadmin:domadmins ${new_share}/progs";
     print "$command\n";
     system($command); 
}



############################################################
# sub
############################################################

sub fetch_old_home {
    my ($user)=@_;
    my $old_home="";
    # look up homes in old passwd
    open(OLD, "<${dir_old_files}/passwd");
    while (<OLD>){
       my @list=split(/:/);
       if ($list[0] eq $user){
          $old_home=$list[5]."/";            
       }
    }
    close(OLD);
    return $old_home;
}



sub fetch_new_home {
    my ($user)=@_;
    my $new_home;
    # look up new homes  in passwd
    setpwent();
    while (my @list=getpwent()) {
     if ($list[0] eq $user){
          $new_home=$list[7]."/";
       }
    }
    endpwent();
    return $new_home;
}



sub configure_quota {
    my ($old_quota,$old_mailquota,$type) = @_;
    #print "OLD: ---$old_quota---\n";
    #print "OLDMAIL: ---$old_mailquota---\n";

    my @old_quota=split(/\+/,$old_quota);
    my @new_quota=();
    my $new_mailquota="mailquota";

    # process quota map
    while(my ($new, $old) = each(%quota_map)) {
        $new_quota[$new]=$old_quota[$old];
    }

    # process new quota
    if ($type eq "teacher"){
        while(my ($new, $value) = each(%new_quota_teacher)) {
            $new_quota[$new]=$value;
        }
    } elsif ($type eq "classes"){
        while(my ($new, $value) = each(%new_quota_classes)) {
            $new_quota[$new]=$value;
        }
    }

    my $new_quota=join("+",@new_quota);

    # process mailquota map
    if ($mailquota_map!=-1){
        $new_mailquota=$old_quota[$mailquota_map];
    }

    # process new mailquota 
    if ($type eq "teacher"){
        if ($new_mailquota_teacher!=-1){
            $new_mailquota=$new_mailquota_teacher;
        }
    } elsif ($type eq "classes"){
        if ($new_mailquota_classes!=-1){
            $new_mailquota=$new_mailquota_classes;
        }
    }
    #print "NEW: ---$new_quota---\n";
    #print "NEWMAIL: ---$new_mailquota---\n";
    return ($new_quota,$new_mailquota);
}


sub fetch_hw_classes {
    my @hw_classes=();
    my %hw_classes=();
   open (WORKSTATIONS,"<$old_ws_file");
   while (<WORKSTATIONS>){
      chomp();
      if (m/^\#/){
          next;
      }

      my ($room,$host,$hwk,$mac,$ip,$netmask,
          $part1,$part2,$part3,$part4,$pxe,$type) = split(/;/);
      if (not defined $host){
         next;
      }
      if ($pxe eq "0"){
         next;
      }
      # add to hash if not there already
      if (not exists $hw_classes{$hwk}){
          #print "added $hwk\n";
          $hw_classes{$hwk}="dummy";
      }
   }
   close (WORKSTATIONS);

   while(my ($key, $value) = each(%hw_classes)) {
      # do something with $key and $value
      #print "$key    $value \n";
      push @hw_classes, $key;
   }
   @hw_classes = sort @hw_classes;
   return @hw_classes;
}


sub rsync_dirs {
    my @dirlist = @_;
    foreach my $entry (@dirlist){
        my ($old,$new)=split(/::/,$entry);
        print"  - OLD: $old\n",
             "    NEW: $new\n";
        system("mkdir -p $new");
        $command="/usr/bin/rsync -e \"ssh -i $key_dsa\" -avz --copy-dirs --keep-dirlinks $delstr  root\@${server}:$old $new";
        print "$command\n";
        system($command); 
    }
}


sub get_conf_lines {
    my ($name) = @_;
    
    my $file = "${DevelConf::vampire_conf}/${name}";
    print "\n### Reading List of files from ${DevelConf::vampire_conf}/${name}\n";
    my @filelist = ();
    open(FILES,"<$file") || die "Cannot open $file: $!";
    while (<FILES>){
	chomp();
        s/^ //g; # Leerzeichen am Zeilenangfang entfernen
        if(/^\#/ or $_ eq ""){ # # am Anfang bedeutet Kommentarzeile
          next;
        }      
        push @filelist, $_;
    }
    close(FILES);
    return @filelist;
}



