#!/usr/bin/perl
use strict;
use Data::Show;
use File::Stat;
use DateTime;
use Text::CSV;
use Text::Diff;
use Mojo::Template;
use MIME::Lite;
use Net::FTP;
use File::Stat;
my $stderrs;
use Tie::STDERR \&stderrs;
use warnings; no warnings 'uninitialized';

my $dir = '/home/sites/clm.dmadelivers.com/www/clmapp/public/files/opf/';
my $tdir = '/home/sites/clm.dmadelivers.com/www/clmapp/templates/root/';
my $url = "http://clm.dmadelivers.com/api/customer/report/export_itn?key=b59597f8-42f5-48b9-8cbb-9a60348821c2";
my $dt = DateTime->now();
my $started = $dt->epoch();
my $specs = {};
my $mt = Mojo::Template->new;

my $host= 'axn.amphire.com';
my $user = 'ftpdma207';
my $pass = 'kI7RUzEt';
my $ftpdir = '/';
my $fdir = '/home/sites/clm.dmadelivers.com/www/clmapp/public/files/opf/';
# my $file = $fdir . $ARGV[0];
my $opflog = '/tmp/download.opf.txt';
unlink($opflog) if -e $opflog;
open(my $fh, '>', $opflog) or warn "Could not open file '$opflog' $!";
close $fh;


# ftp://axn.staging.amphire.com / ftpdma207 / faWrudr5
# ftp://axn.amphire.com/  / ftpdma207 / kI7RUzEt

# get new
my $cmd = '/usr/bin/wget -P ' . $dir  . ' --content-disposition "' . $url . '" 2>&1';
my @res = `$cmd`;

# show @res;

	# find last
	opendir(my $dh, $dir);
	chdir($dir);
	my @files = sort { (stat($a))[10] <=> (stat($b))[10] } (readdir($dh));
	closedir($dh);
	my @opffiles;
	foreach my $f (@files){
		push(@opffiles, $f) if $f =~ /DMAOPF\d+\.TXT$/;
	}
	# show @opffiles;

	my $last = $dir . $opffiles[-2];
	my $new = $dir . $opffiles[-1];
	my $newf = $opffiles[-1];
	my $newdt;
	if($new =~ /DMAOPF(\d+)\.TXT/){
		$newdt = $1;
		unlink($dir . 'DMAOPF' . $1 . '.TXT.1');
	}


	if(!-f $new){
		# ERROR file didn't download
	}
	if(!-f $last){$last = $new;}

	# file mods

	my $lstat = new File::Stat($last);
	my $nstat = new File::Stat($new);
	$specs->{now} = $dt->epoch;
	$specs->{datetime} = scalar localtime($specs->{now});
	$specs->{last}->{filepath} = $last;
	$specs->{new}->{filepath} = $new;
	$specs->{last}->{mtime} = $lstat->mtime;
	$specs->{new}->{mtime} = $nstat->mtime;
	$specs->{last}->{datetime} = scalar localtime($lstat->mtime);
	$specs->{new}->{datetime} = scalar localtime($nstat->mtime);
	$specs->{last}->{size} = $lstat->size;
	$specs->{new}->{size} = $nstat->size;

	$specs->{diff}->{size} = $specs->{new}->{size} - $specs->{last}->{size};
	$specs->{diff}->{mtime} = sprintf("%.2f", ($specs->{new}->{mtime} - $specs->{last}->{mtime}) / 60);


	my $diff = diff $last, $new, { STYLE => "OldStyle" };
	# open(my $fh, '>', $dir . 'diff' . $newdt . '.txt') or die "Could not open diff file $!";
	# print $fh $diff;
	# close $fh;

	my @diff = split(/\r?\n/, $diff);
	$specs->{diff}->{filediff} = \@diff;

	&readfile($new,$specs->{new});
	&readfile($last,$specs->{last});
	$specs->{diff}->{active} = $specs->{new}->{active} - $specs->{last}->{active};
	$specs->{diff}->{inactive} = $specs->{new}->{inactive} - $specs->{last}->{inactive};
	$specs->{diff}->{systemcnt} = $specs->{new}->{systemcnt} - $specs->{last}->{systemcnt};
	$specs->{diff}->{bpcnt} = $specs->{new}->{bpcnt} - $specs->{last}->{bpcnt};
	$specs->{diff}->{rowcnt} = $specs->{new}->{rowcnt} - $specs->{last}->{rowcnt};

	my $body = $mt->vars(1)->render_file($tdir . '/diff.opf.html.ep', { newfile => $newf, specs => $specs});

	# do upload

	my $stat = new File::Stat($new);
	print STDERR "UPLOAD: $new " . scalar localtime( $stat->mtime ) . " " . $stat->size . "bytes\n";

	# exists, not zero-bytes, and is less than 1 minute old
	if(-e $new && -s $new){   # && time() < $stat->mtime + 60 
		my $ftp = Net::FTP->new($host, Passive => 1, Debug => 1) or die "Cannot connect to some.host.name: $@";
		$ftp->login($user,$pass) or die "Cannot login ", $ftp->message;
		$ftp->cwd($ftpdir) or die "Cannot change working directory ", $ftp->message;
		my $uploaded = $ftp->put($new) or die "put failed ", $ftp->message;
		my $uploaded2 = $ftp->put('/home/sites/clm.dmadelivers.com/www/clmapp/templates/eot.txt') or die "put failed ", $ftp->message;
		$ftp->quit;

	}else{
		print "ERROR: File $new does not exist or is zero bytes or is too old.\n";
	}





	my $msg = MIME::Lite->new(
		From     => 'root@dmadelivers.com',
		# Bcc => 'dma@ace4it.com',
		# To => 'dma@ace4it.com',
		To => 'opfftp@dmadelivers.com',
		# To => 'matt.kot@dmadelivers.com',
		# Cc => 'jim.szatkowski@dmadelivers.com',
	    Subject  => 'OPF FTP Review: ' . $specs->{datetime},
		Type => 'multipart/mixed'
	);
	$msg->attach(
		Type     => 'text/html',
		Data => $body
	);
	# if(-e $opflog){

	# 	local *STDERR; untie *STDERR;

	# 	$msg->attach(
	# 	    	Type     => 'text/plain',
	# 	        Path     => $opflog,
	# 	);
	# }
	$msg->send;



# show $specs;

sub readfile{
	my $file = shift;
	my $spec = shift;


	my $csv = Text::CSV->new ( { binary => 1, sep_char => "\t", } ) or die "Cannot use CSV: ".Text::CSV->error_diag ();
	open my $fh, "<:encoding(utf8)", $file or die "test.csv: $!";
	my @rows;
	my $active; my $system;
	while ( my $row = $csv->getline( $fh ) ) {
		$spec->{active}++ if $row->[11] == 1;
		$spec->{inactive}++ if $row->[11] == 2;
		$spec->{systemcnt}++ if $row->[24] ne "";
		$spec->{bpcnt}++ if $row->[25] == 1;
		$spec->{rowcnt}++;
	}


}


sub stderrs{
	my $line = shift;

	open(my $fh, '>>', $opflog) or warn "Could not open file '$opflog' $!";
	print $fh $line;
	close $fh;

}

1;
