#!/usr/bin/perl

#
#   Copyright (C) Dr. Heinz-Josef Claes (2002-2004)
#                 hjclaes@web.de
#   
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#   
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#   
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#


my $VERSION = '$Id: storeBackupls.pl 335 2004-07-23 03:56:18Z hjc $ ';
push @VERSION, $VERSION;

use strict;


sub libPath
{
    my $file = shift;

    my $dir;

    # Falls Datei selbst ein symlink ist, solange folgen, bis aufgelst
    if (-f $file)
    {
	while (-l $file)
	{
	    my $link = readlink($file);

	    if (substr($link, 0, 1) ne "/")
	    {
		$file =~ s/[^\/]+$/$link/;
	    }
	    else
	    {
		$file = $link;
	    }
	}

	($dir, $file) = &splitFileDir($file);
	$file = "/$file";
    }
    else
    {
	print STDERR "<$file> does not exist!\n";
	exit 1;
    }

    $dir .= "/../lib";           # Pfad zu den Bibliotheken
    my $oldDir = `/bin/pwd`;
    chomp $oldDir;
    if (chdir $dir)
    {
	my $absDir = `/bin/pwd`;
	chop $absDir;
	chdir $oldDir;

	return (&splitFileDir("$absDir$file"));
    }
    else
    {
	print STDERR "<$dir> does not exist, exiting\n";
    }
}
sub splitFileDir
{
    my $name = shift;

    return ('.', $name) unless ($name =~/\//);    # nur einfacher Dateiname

    my ($dir, $file) = $name =~ /^(.*)\/(.*)$/s;
    $dir = '/' if ($dir eq '');                   # gilt, falls z.B. /filename
    return ($dir, $file);
}
my ($req, $prog) = &libPath($0);
push @INC, "$req";

require 'checkParam.pl';
require 'dateTools.pl';
require 'version.pl';
require 'storeBackupLib.pl';
require 'prLog.pl';
require 'readKeyFromFile.pl';
require 'storeBackupLib.pl';

$main::keepAll = '30d';
$main::keepDuplicate = '7d';
$main::checkSumFile = '.md5CheckSums';
$main::chmodMD5File = '0600';

my $Help = <<EOH;
Lists backup directories generated with storeBackup.pl with week day.

usage:
    $prog [-f configFile] [storeBackup-dir]
    $prog [-v] storeBackup-dir

--verbose   -v  additional informations about the backup directories
--file      -f  configuration file; analyse backups depending on
		keep parameters in configuration file
storeBackup-dir directory where the storeBackup directories are
		overwrites the path in the config file if used with -f

Copyright (c) 2002-2004 by Heinz-Josef Claes
Published under the GNU General Public License
EOH
    ;

my $checkSumFile = '.md5CheckSums';

&printVersions(\@ARGV, '-V');

my $CheckPar =
    CheckParam->new('-allowLists' => 'yes',
		    '-list' => [Option->new('-option' => '-v',
					    '-alias' => '--verbose'),
				Option->new('-option' => '-f',
                                            '-alias' => '--file',
                                            '-param' => 'yes')
				]);

$CheckPar->check('-argv' => \@ARGV,
                 '-help' => $Help
                 );

my $verbose = $CheckPar->getOptWithoutPar('-v');
my $configFile = $CheckPar->getOptWithPar('-f');

my ($dir) = $CheckPar->getListPar();
die "$Help" unless $dir or $configFile;

my $today = dateTools->new();

if ($configFile)
{
    &analyseOldBackups($dir, $configFile, $today);
    exit 0;
}

opendir(DIR, $dir) or
    die "cannot open <$dir>";
my ($entry, @entries);
while ($entry = readdir DIR)
{
    my $e = "$dir/$entry";
    next if (-l $e and not -d $e);
    push @entries, $entry;
}
closedir(DIR);

my $prLog = printLog->new();
my $i = 1;
foreach $entry (sort @entries)
{
    next unless $entry =~
	/\A(\d{4})\.(\d{2})\.(\d{2})_(\d{2})\.(\d{2})\.(\d{2})\Z/o;
    my $d = dateTools->new('-year' => $1,
			   '-month' => $2,
			   '-day' => $3);
    printf "%3d  ", $i++;
    print $d->getDateTime('-format' => '%W %X %D %Y'), "   $entry   ",
    $today->deltaInDays('-secondDate' => $d);
    print "  not finished" if (-e "$dir/$entry/$checkSumFile.notFinished");
    print "\n";

    if ($verbose)
    {
	my $rcsf = readCheckSumFile->new('-checkSumFile' =>
					 "$dir/$entry/$checkSumFile",
					 '-prLog' => $prLog);

	my $metaVal = $rcsf->getMetaVal();
	my $metaKey = $rcsf->getMetaKey();
	my $key;
	foreach $key (@$metaKey)
	{
	    print "\t$key -> <", $$metaVal{$key}, ">\n";
	}
	$rcsf->DESTROY();
    }
}

exit 0;


######################################################################
sub analyseOldBackups
{
    my ($dir, $configFile, $today) = @_;

    my $prLog = printLog->new('-withTime' => 'no',
			      '-withPID' => 'no');
    my $rcf = readConfigFile->new('-configFile' => $configFile,
				  '-print' => undef,
				  '-prLog' => $prLog,
				  '-tmpdir' => undef,
				  '-compress' => undef,
				  '-uncompress' => undef,
				  '-postfix' => undef,
				  '-noCompress' => undef,
				  '-queueCompress' => undef,
				  '-noCopy' => undef,
				  '-queueCopy' => undef,
				  '-exceptSuffix' => [],
				  '-chmodMD5File' => $main::chmodMD5File,
				  '-keepAll' => $main::keepAll,
				  '-keepDuplicate' => $main::keepDuplicate,
				  '-logInBackupDirFileName' => undef);

    $dir = $rcf->get('targetDir') unless $dir;
    my $keepAll = $rcf->get('keepAll');
    my $keepWeekday = join(' ', @{$rcf->get('keepWeekday')});
    my $keepFirstOfYear = $rcf->get('keepFirstOfYear');
    my $keepLastOfYear = $rcf->get('keepLastOfYear');
    my $keepFirstOfMonth = $rcf->get('keepFirstOfMonth');
    my $keepLastOfMonth = $rcf->get('keepLastOfMonth');
    my $firstDayOfWeek = $rcf->get('firstDayOfWeek');
    my $keepFirstOfWeek = $rcf->get('keepFirstOfWeek');
    my $keepLastOfWeek = $rcf->get('keepLastOfWeek');
    my $keepDuplicate = $rcf->get('keepDuplicate');
    my $keepMinNumber = $rcf->get('keepMinNumber');
    my $keepMaxNumber = $rcf->get('keepMaxNumber');

    my $statDelOldBackupDirs =
	statisticDeleteOldBackupDirs->new('-prLog' => $prLog);
    my $delOld =
	deleteOldBackupDirs->new('-targetDir' => $dir,
				 '-doNotDelete' => undef,
				 '-checkSumFile' => $main::checkSumFile,
				 '-prLog' => $prLog,
				 '-today' => $today,
				 '-keepFirstOfYear' => $keepFirstOfYear,
				 '-keepLastOfYear' => $keepLastOfYear,
				 '-keepFirstOfMonth' => $keepFirstOfMonth,
				 '-keepLastOfMonth' => $keepLastOfMonth,
				 '-firstDayOfWeek' => $firstDayOfWeek,
				 '-keepFirstOfWeek' => $keepFirstOfWeek,
				 '-keepLastOfWeek' => $keepLastOfWeek,
				 '-keepAll' => $keepAll,
				 '-keepWeekday' => $keepWeekday,
				 '-keepDuplicate' => $keepDuplicate,
				 '-keepMinNumber' => $keepMinNumber,
				 '-keepMaxNumber' => $keepMaxNumber,
				 '-statDelOldBackupDirs' =>
				 $statDelOldBackupDirs,
				 '-alsoCheckLastBackup'  => 'yes',
				 '-flatOutput' => 'yes'
				 );
    $delOld->checkBackups();
}
