#!/usr/bin/perl -w
# This script (sophomorix-project) is maintained by Rüdiger Beck
# It is Free Software (License GPLv3)
# If you find errors, contact the author
# jeffbeck@web.de  jeffbeck@linuxmuster.net

# modules
use strict;
#use Quota;
use Getopt::Long;
Getopt::Long::Configure ("bundling");
use Data::Dumper;
$Data::Dumper::Indent = 1;
$Data::Dumper::Sortkeys = 1;
$Data::Dumper::Useqq = 1;
$Data::Dumper::Terse = 1; 

my @arguments = @ARGV;
my @log=();

# ===========================================================================
# config
# ==========================================================================
my $config="/usr/share/sophomorix-dump/migration-6-to-7.conf";
my $target_topdir="/root/sophomorix-dump";
my $target_dir="/root/sophomorix-dump/data"; 
my $project_dump="/root/sophomorix-dump.projects";
my $view_dumps_dir = "/root/sophomorix-dump-viewdumps";

# ===========================================================================
# Optionen verarbeiten
# ==========================================================================

# Variablen für Optionen
my $help=0;
my $verbose=0;
my $clean=0;

# Parsen der Optionen
my $testopt=GetOptions(
           "help|h" => \$help,
           "verbose|v+" => \$verbose,
           "clean" => \$clean,
         );

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

# --help
if ($help==1) {
   # Scriptname ermitteln
   my @list = split(/\//,$0);
   my $scriptname = pop @list;
   # Befehlbeschreibung
   print('
sophomorix-dump dumps users, classes, projects and workstations from a linuxmuster.net 6.x server 

Usage:

Dump the data:

   sophomorix-dump

Clean up after dump (delete the dumped data):

   sophomorix-dump --clean

Options
  -h  / --help
  -v  / --verbose
  -vv / --verbose --verbose

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



if ($clean==1){
    print "Cleaning up dump\n";
    my $command="rm -rf /root/sophomorix-dump";
    print "   $command\n";
    system($command);
    my $command2="rm -f /root/sophomorix-dump.projects";
    print "   $command2\n";
    system($command2);
    my $command3="rm -rf /root/sophomorix-dump-viewdumps";
    print "   $command3\n";
    system($command3);
   

    exit;
}



if (-e $target_topdir){
    print "\n";
    print "ERROR: The  directory for the dump exists already: $target_topdir\n\n";
    print "       Use  \"sophomorix-dump --clean\"  to delete the previous dump\n\n";
    exit;
}

if (-e $project_dump){
    print "\n";
    print "ERROR: The  directory for the project dump exists already: $project_dump\n\n";
    print "       Use  \"sophomorix-dump --clean\"  to delete the previous dump\n\n";
    exit;
}

if (-e $view_dumps_dir){
    print "\n";
    print "ERROR: The  directory for the view dumps exists already: $view_dumps_dir\\n";
    print "       Use  \"sophomorix-dump --clean\"  to delete the previous dump\n\n";
    exit;
}



############################################################
# dumping data
############################################################                        

print "Starting data dump\n";

# dump postgres database views
system("/usr/sbin/sophomorix-dump-postgres-views.sh $view_dumps_dir");

# dump projects
system("/usr/sbin/sophomorix-project --dump $project_dump");


# copy relevant files from server                                    
&copy_files();



############################################################
# print results
############################################################
print "\n";
print "########### Start: Results of dump ##########\n";
foreach my $line (@log){
    print $line;
}
print "########### End: Results of dump ##########\n";
print "WARNINGs in Results of dump are OK:\n";
print "\n";
print "  /etc/sophomorix/virusscan/sophomorix-virusscan-excludes.conf\n";
print "  /etc/sophomorix/virusscan/sophomorix-virusscan.conf\n";
print "  /var/lib/sophomorix/virusscan/penalty.db\n";
print "    are only needed, if you had configured sophomorix for scanning viruses\n";
print "\n";

exit;





############################################################
# subs
############################################################

sub copy_files {
    #system("mkdir -p");
    open(CONFIG,"<$config") || die "$config not found";
    while(<CONFIG>){
        if(/^\#/){ # # am Anfang bedeutet Kommentarzeile
	    next;
        }
        chomp();
        my ($old_path,$new_path,$new_permissions,$may_must,$type)=split(/::/);
        my $old_path_dump=$target_dir.$old_path;
        print "   * Saving: $old_path\n";
        print "        to : $old_path_dump\n";

        # copying stuff
        if ($type eq "dir"){
            # directory
            system("mkdir -p $old_path_dump");
            my $command="cp -r $old_path/. $old_path_dump";
            #print "$command\n";
            system($command);
        } elsif ($type eq "file"){
            # file
            system("install -D   $old_path $old_path_dump");
        }

        # testing if copy was secessful
        if ($type eq "dir" and -d $old_path_dump){
            print "   * Diretory Dump OK: $old_path_dump\n";
            push @log, "    * Directory Dump OK: $old_path_dump\n";
	} elsif (-f $old_path_dump and -s $old_path_dump){
            print "   * Dump OK: $old_path_dump\n";
            push @log, "    * Dump OK: $old_path_dump\n";
	} elsif (-f $old_path_dump and -s $old_path_dump and $may_must eq "may") {
            print "WARNING, not dumped: $old_path_dump\n";
            print "   This may be the result of an unused feature\n";
	} else {
            if ($may_must eq "must"){
                print "$may_must\n";
                print "ERROR dumping $old_path_dump\n";
                push @log, "ERROR dumping: $old_path_dump\n";
	    } elsif ($may_must eq "may"){
                print "$may_must\n";
                print "WARNING dumping $old_path_dump (may be an unused feature)\n";
                push @log, "WARNING dumping: $old_path_dump\n";
            } else {
                print "ERROR IN SCRIPT: $may_must -> $old_path needs must/may entry\n";
            }
        }
   }
    close(CONFIG);
}

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 {
      if($verbose>=3){
         print "All options  were recognized.\n";
      }
   }
}
