#!/usr/bin/perl
use strict;
use Getopt::Long;
use OpMon;
use File::Copy;

$ENV{"USER"}="opuser";
$ENV{"HOME"}="/home/opuser";

sub usage {
	print "Usage:\n";
	print "\t$0 -u <smb user> -p <smb pass> -s <share path(including server name)> -r <scheduled report name>\n";
	exit($CRITICAL);
}

sub main {

	my @aux;
	my %db;
	my %user_opt;
	my %smbinfo;
	my $sth;
	my $ret;
	my $q;
	my $row;
	my $pdf_file;
	my $new_pdf_file;
	my $file_name;
	my $today;

	GetOptions(
	            "u=s" => \$user_opt{'user'},
	            "p=s" => \$user_opt{'pass'},
	            "s=s" => \$user_opt{'path'},
	            "r=s" => \$user_opt{'report_name'},
	            "w=s" => \$user_opt{'workgroup'}
	);

	if ( !defined($user_opt{'user'}) || 
	     !defined($user_opt{'pass'}) ||
	     !defined($user_opt{'path'}) ||
	     !defined($user_opt{'report_name'}) ) {

		usage();
	}

	$ret = opmon_parse_db_config(\%db);
	if ($ret != $OK) {
		print "DESCONHECIDO - Impossivel encontrar credenciais para acesso ao banco de dados\n";
		exit($UNKNOWN);
	}

	$db{'DBNAME'} = "opmon4";

	$q = "select * from scheduled_reports_logs where date >= curdate()";

	$sth = opmon_do_query(\%db,$q);
	$pdf_file = $CRITICAL;
	while( $row = $$sth->fetchrow_hashref() ) {
		if ($$row{'message'} =~ m/^PDF file: (.+$user_opt{'report_name'}\.pdf)$/) {
			$pdf_file = $1;
			last;
		}
	}

	if ($pdf_file == $CRITICAL || !-f $pdf_file) {
		print "ALERTA - Relatorio nao agendado ou nao gerado\n";
		exit($WARNING);
	}

	$ret = opmon_test_smb_share(\%user_opt);
	if ($ret == $CRITICAL) {
		print "CRITICAL - Impossivel acessar compartilhamento ".$user_opt{'path'}."\n";
		exit($CRITICAL);
	}

	#@aux = split(/\//,$pdf_file);
	#$file_name = $aux[$#aux];
	#@aux = localtime(time);
	#if ($aux[4] < 10) {
	#	$aux[4] = "0".$aux[4];
	#}
	#if ($aux[3] < 10) {
	#	$aux[3] = "0".$aux[3];
	#}

	#$today = $aux[3]."-".$aux[4]."-".$aux[5];
	#@aux = split(/\./,$file_name);
	#$file_name = $aux[0]."-".$today.".pdf";

	#$new_pdf_file = "/tmp/".$file_name;
	#$ret = copy($pdf_file,$new_pdf_file);
	#if (!$ret) {
	#	print "CRITICAL - Impossivel efetuar copia do arquivo antes da transferencia\n";
	#	exit($CRITICAL);
	#}

	#$ret = opmon_copy_file_to_smb(\%user_opt,$new_pdf_file);
	$ret = opmon_copy_file_to_smb(\%user_opt,$pdf_file);
	if ($ret == $CRITICAL) {
		print "CRITICAL - $!\n";
		exit($CRITICAL);
	}


	print "OK - Arquivo $pdf_file copiado para $user_opt{'path'} com sucesso\n";
	exit($OK);

}

main();
