#!/usr/bin/perl -w
# This script (get_marks_from_teamdrive) was created by Rüdiger Beck
# It is released under the GPL Version 3
# For Bugs send mail to:
# jeffbeck@web.de

use File::Basename;
use Getopt::Long;
my $home = $ENV{'HOME'};


my $help=0;
my $result=0;

# Parsen der Optionen
my $testopt=GetOptions(
           "help|h" => \$help,
           "result|r" => \$result,
          );

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


# --help
if ($help==1) {
   # Scriptname ermitteln
   my @list = split(/\//,$0);
   my $scriptname = pop @list;
   # Befehlsbeschreibung
   print('
get_marks_from_teamdrive fetches all collect files from teamdrive to exampliy

Step by step (Collect):
  A) copy this script into the root of an examplix project
  B) create a teamrive space with the same name of the project
  C) copy the collect/exam/*.xls files that you want to collect 
     to the top directory of the teamdrive space 
  D) you can import teamdrive modifications by running
     ./get_marks_from_teamdrive

Step by step (Results):

  A) Create results:
     examplix -r .......
  B) Display them in teamdrive:
     ./get_marks_from_teamdrive -r


Troubleshooting:

The spaces-path to the teamdive spaces ist saved in: $HOME/.teamdrive/teamdrive.settings
But not always, ONLY when you CHANGE it. 
So change this path, and change it back to save it in this file.

Options
  -h  / --help


');
   print "\n";
   exit;
}



############################################################

my $spaces_path=&get_spaces_path();
my $project=&get_project_name();

if ($result==1){
    &cp_results($spaces_path,$project);
} else {
    &test_collect_files($spaces_path,$project);
}



sub cp_results {
    my ($spaces,$pro)=@_;
    my $cp_target=$spaces.$pro;
    my $result_source_1="./results/exam/kammer-".$pro.".pdf";
    print "\nSource 1 from examplix:\n";
    print "   $result_source_1\n";

    my $result_source_2="./results/exam/results-".$pro.".pdf";
    print "\nSource 2 from examplix:\n";
    print "   $result_source_2\n";

    print "\nTarget in teamdrive:\n";
    print "    $cp_target\n";

    system("cp -v $result_source_1 $cp_target");
    system("cp -v $result_source_2 $cp_target");


}



sub test_collect_files {
    my ($spaces,$pro)=@_;
    my $collect_source=$spaces.$pro;
    my $collect_target="./collect/exam";
    print "\nSource from teamdrive:\n";
    print "    $collect_source\n";

    print "\nTarget in project:\n";
    print "   $collect_target\n";
    opendir COLL, $collect_target or die "Fehler: $!";

    # walk through all files in examplix
    print "\n";
    print "Analyzing files:\n";

    foreach my $filename (readdir COLL){
        my $file=$collect_target."/".$filename;
        my $source_file=$collect_source."/".$filename;
        if (-f $file){
           if (-f $source_file){
               print "\n";
               print "   OK: file in teamdrive found\n";
               print "   # fetching:  $source_file\n";
               print "   # to target: $file\n";
               # do it diff: 
               # echo 0 -> identical
               # echo 2 -> verschieden
               my $diff=system("diff $source_file $file > /dev/null");
               if ($diff==0){
                   print "   # File unchanged: nothing to fetch from teamdrive to examplix\n";
                   print "\n";
               } else {
                   print "   # File has changed: fetching from teamdrive to examplix\n";
                   system("cp $source_file $file");
                   print "\n";
               }
          } else {
 	       print "   * Skipped file: $source_file\n";
           }
        } else {
	    print "   * Skipped dir:  $source_file\n";
        }
    }
}



sub get_project_name {
    my $abs_dir=`pwd`;
    chomp($abs_dir);
    my $examplix_name=basename($abs_dir);
    print "   * examplix Project name is >$examplix_name<\n";
    return $examplix_name;
}



sub get_spaces_path {
    my $config_file=$home."/.teamdrive/teamdrive.settings";
    open (TDCONF, $config_file) || die "Fehler: $!";
    while(<TDCONF>){
        chomp;
        my ($key,$value)=split(/=/);
        if ($key eq "spaces-path"){
            print "   * Teamdrive spaces are in >$value<\n";
            if (-d $value){
                return $value;
            } else {
                print "ERROR: dir $value does not exist\n";
                exit;
            }
        }
    }
    close(TDCONF);
}


sub  check_options{
   my ($parse_ergebnis) = @_;
   if (not $parse_ergebnis==1){
      my @list = split(/\//,$0);
      my $scriptname = pop @list;
      print "\nYou have made a mistake, when specifying options.\n"; 
      print "See error message above. \n\n";
      print "... $scriptname is terminating.\n\n";
      exit;
   } else {
      print "All options  were recognized.\n";
   }

}
