#! /usr/bin/perl

use DBI;
use Getopt::Long;
use strict;
require "/usr/local/bin/backupCred.pm";

our $NAS_ROOT;
my $bakSourceUUID="";
my $bakSourceDir="";
my $bakDuration;
my $bakResult;
my $bakTargetUUID=`findmnt $NAS_ROOT -no UUID`;
$bakTargetUUID =~ s/\s+$//;
#print "bakTarget default:$bakTargetUUID:\n";
our $database;
our $dbusername;
our $dbpassword;

#print "Artguments: @ARGV\n";
GetOptions('srcid=s' => \$bakSourceUUID,
	'srcdir=s' => \$bakSourceDir,
	'targetid=s' => \$bakTargetUUID,
	'duration=n' => \$bakDuration,
	'result=n' => \$bakResult,
	'help' => sub { usage() } ) or usage();

#print "SUUID:$bakSourceUUID: SD:$bakSourceDir: TUUID:$bakTargetUUID:\n";
binmode(STDOUT,":utf8");

my $dbh=DBI -> connect("dbi:Pg:host=localhost;dbname=$database",$dbusername,$dbpassword,
	{AutoCommit => 0, RaiseError => 1})
	or die "cannot connect to database $DBI::errstr\n";

# test if the media already exits
my $sth=$dbh->prepare("select count(*) from \"tMedia\" where \"mediaUUID\" ilike ?");
#print "sth: $sth\n";
$sth->execute($bakSourceUUID);
if ($sth->err) {
	die ("execution failed: $dbh->errstr()");
}
my ($count)=$sth->fetchrow_array;
$sth->finish();
#print "************* count:$count\n";
if ($count==0){
	print("media does not exist in database. Trying to insert...\n");
	my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
	$year=$year+1900;
	$mon=$mon+1;
	$sth=$dbh->prepare("insert into \"tMedia\" (\"mediaName\",\"mediaUUID\",\"mediaIsActive\") VALUES ('discovered $year-$mon-$mday $hour:$min:$sec',?,true)");
	$sth->execute($bakSourceUUID);
	if ($sth->err) {
		die ("insert failed: $dbh->errstr()");
	}
}
$dbh->commit();

my $sth=$dbh->prepare(<<SQL);
INSERT INTO "tBackup" ("bakSourceUUID","bakSourceDir","bakTargetUUID","bakDurationSec","bakResult")
VALUES (?, ?, ?, ?, ?)
SQL
$sth->execute($bakSourceUUID,$bakSourceDir,$bakTargetUUID,$bakDuration,$bakResult);
$sth->finish();
$dbh->commit;
$dbh->disconnect or warn $dbh->errstr;
#print "SUUID:$bakSourceUUID: SD:$bakSourceDir: TUUID:$bakTargetUUID:\n";
exit(0);

sub	usage()
{
print << "EOF";

Update backup database.
Is usually called after a backup.
usage: $0 --srcid=<UUID> --srcdir=<dir> --targetid=<UUID> --duration=<sec> --result=<result code>
  srcid    : UUID of source disk
  srcdir   : directory successfully backed up
  targetid : UUID of target disk
  duration : duration of backup in seconds
  result   : Exit Code of e.g. the Rsync Operation

EOF
exit;
}

