#!/usr/bin/perl -w
# $Id$
# This script (sophomorix-support) 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;
Getopt::Long::Configure ("bundling");

use DBI;

use Sophomorix::SophomorixConfig;
use Sophomorix::SophomorixBase;
use Sophomorix::SophomorixPgLdap qw(db_connect
                                    db_disconnect
                                    export_userdata_upgrade
				    );

# Variablen für Optionen

my @arguments = @ARGV;
my $config_file="/usr/share/sophomorix/devel/sophomorix-support.conf";
my $create_dir="/root/sophomorix-support";
my $logfile="support.log";

my $hostname=`hostname -s`;
chomp($hostname);
my $dnsdomainname=`dnsdomainname`;
chomp($dnsdomainname);
my $timestamp = `date '+%Y-%m-%d_%H-%M'`;
chomp($timestamp);
my $treename=$hostname.".".$dnsdomainname."-".$timestamp;
my $support_tree="${create_dir}/${treename}";
my $upgrade_path_fs="/var/upgrade/linuxmuster/sophomorix2";
my $upgrade_path_data="/var/upgrade/linuxmuster/sophomorix2-data";
my $db_dump="${DevelConf::log_pfad}/current-ldap.sql";


$Conf::log_level=1;
my $help=0;
my $info=0;
my $add_files="";
my @add_files=();
my $add_dirlists="";
my @add_dirlists=();
my $path="";
my $prepare_dist_upgrade=0;
my $unlock=0;
my $zip=1;

# this script skips the lock automatically
my $skiplock=1;
push @arguments, "--skiplock";

# Parsen der Optionen
my $testopt=GetOptions(
           "help|h" => \$help,
           "info|i" => \$info,
           "add-files=s" => \$add_files,
           "add-dirlists=s" => \$add_dirlists,
           "path=s" => \$path,
           "zip!" => \$zip,
           "unlock" => \$unlock,
           "prepare-dist-upgrade" => \$prepare_dist_upgrade,
          );

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


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



# setting variables
# --prepare-dist-upgrade
if ($prepare_dist_upgrade==1){
    $zip=0;
    $path=$upgrade_path_fs;
    if (-e $path){
        print "Cleaning previous version of prepare-dist-upgrade files\n";
        system("rm -rf $path");
    }
    &export_userdata_upgrade($upgrade_path_data);
}

# --path
if ($path ne ""){
    $support_tree="${path}";
} else {
    $support_tree="${create_dir}/${treename}";
}



# --help
if ($help==1) {
   # Scriptname ermitteln
   my @list = split(/\//,$0);
   my $scriptname = pop @list;
   # Befehlbeschreibung
   print "\n$scriptname packages files to be sent to the support.\n\n";
   print "WARNING: These files contain sensible data! Do not send unencrypted!\n\n";
   print('
Options
  -h  / --help
  -i  / --info
  --add-files file1,file2,...        (absolute paths)
  --add-dirlists dir1,dir2,...       (absolute paths)

  --zip   (default)
  --nozip

  --path /path/to/saved/files

  --prepare-dist-upgrade 
');
   print "    (equal to: --nozip --path $upgrade_path_fs)";
   print('

  --unlock

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






# --info
if ($info==1) {
    my ($ref_files,$ref_dirlist)=&read_config();
    my @files=@$ref_files;
    @files=(@files,@add_files);
    my @dirlist=@$ref_dirlist;
    @dirlist=(@dirlist,@add_dirlists);
    &titel("(1) A dump of database ldap will be made and packaged");
    &titel("(2) These files will be packaged:");
    foreach my $file (@files){
        print "   $file \n";
    }
    &titel("(3)These dirlists will be packaged:");
    foreach my $dir (@dirlist){
        print "   $dir \n";
    }
    exit;
}


&log_script_start(@arguments);


# --unlock
if ($unlock==1){
    # unlock sophomorix with backup
    &unlock_sophomorix();
    &log_script_end(@arguments);
}



# no options 

# prepare
my ($ref_files,$ref_dirlist)=&read_config();
my @files=@$ref_files;
@files=(@files,@add_files);
my @dirlist=@$ref_dirlist;
@dirlist=(@dirlist,@add_dirlists);
system("install -d $support_tree");
open (LOG,">${support_tree}/${logfile}");

# dump the database
&titel("Creating a dump of database ldap");
system("pg_dump --format=p -U ldap --file='$db_dump' ldap");

# creating a tree
# files
&titel("Copying the following files");
foreach my $file (@files){
    print "   $file \n";

    if (-e $file) {
        print LOG "copying:      $file \n";
        system ("install -D $file ${support_tree}${file}");
    } else {
        print LOG "not existing: $file \n";
    }
}
# ls-al files
&titel("Listing contents of the following files");
foreach my $dir (@dirlist){
    print "   $dir \n";

    if (-e $dir) {
        print LOG "ls-al:        Directory $dir \n";
        system ("install -d ${support_tree}${dir}");
        system ("ls -al $dir > ${support_tree}${dir}/ls-al");
    } else {
        print LOG "not existing: Directory $dir \n";
    }
}

close(LOG);


# zipping the tree
if ($zip==1) {
   &titel("Packaging files in ${support_tree}");
   system("cd $create_dir; zip -r  ./${treename}.zip ./${treename}");
   &titel("Deleting created tree in ${create_dir}/${treename}");
   system ("rm -rf ${create_dir}/${treename}");
   print "\n";
   &titel("The following file is ready to be sent to the support:");
   &titel("${create_dir}/${treename}.zip");
   &titel("WARNING: This file contains sensible data!");
   &titel("         Do not send unencrypted!");
}

# cleaning up
print "\n";
&titel("Cleaning up ...");
&titel("Deleting dumped database ${db_dump}");
system ("rm ${db_dump}");


&log_script_end(@arguments);






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


sub read_config {
    my @configs=();
    my @dirlist=();
    open(CONFIG, "<$config_file");
    while (<CONFIG>) {
        if(/^\#/){ # # am Anfang bedeutet Kommentarzeile
            next;
        }
        chomp();
        my $line=$_;
        if ($line ne ""){
	    if ($line=~/^DIRLIST/){
                my ($tag,$dir)=split(/::/,$line);
                push @dirlist, $dir;
            } else {
                push @configs, $line;
            }
        }
    }
    close(CONFIG);
    @configs = sort @configs;
    @dirlist = sort @dirlist;
    return (\@configs,\@dirlist);
}


