#!usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
use JSON::XS qw(encode_json decode_json);
use File::Slurp qw(read_file write_file);
use Getopt::Long qw(GetOptions);

my %config = (
    'uploadPHP' => {
                       'USERNAME' => 'dreamyourmansion',
                       'PASSWORD' => 'H5AZ#dQZ5Ycf',
                       'DEBUG' => 1,
                       'TRUNCATED_DEBUG' => 1,
                       'PROXY_USER' => 'zino%40onlinehome.de',
                       'PROXY_PASSWORD' => 'zinomedial33t',
                       'PROXY_IP' => 'de435.nordvpn.com',
                       'PROXY_PORT' => 80,
    },
    'profile' => undef,
    'imageDir' => './src/images/',
    'SRCRoot'  => './src/',
    'DBFilepath' => '/home/pi/instafeed/src/db/db.dat',
    'uploadPHP_CMD' => '/usr/bin/php /home/pi/instafeed/vendor/mgp25/instagram-php/examples/uploadPhoto.php',
    'uploadPHP_DESCRIPTION_ADD' => "The most beautiful real estates in the world!\n\nBenefit from the flourishing housing market in Germany. Contact us now by DM.\n\nVom Mieter zum Eigentümer! Exklusives Portfolio: Kontaktiere uns jetzt per DM.",
    'uploadPHP_TAGS' => '#investment #immobilie #mansionhouse #dream #poolhouse #villa #realestate #loft #awesome #lifestyle #motivation #luxury',
);

my (%data, %db, %profiles);
my $dbKeysStart = 0;
GetOptions ('profile=s' => \$config{'profile'}) or die "Usage: $0 --profile *name*\n";
die "Usage: $0 --profile *name*\n" if !$config{'profile'} ;

# MAIN

&UndumpFromFile();
#print Dumper \%db;
&DirectoryListing();
# print Dumper \%data;
&FindNewDataset();
&Summary();

sub UndumpFromFile {
    &Delimiter((caller(0))[3]);
    
    if (-e $config{'DBFilepath'}) {
        my $json = read_file($config{'DBFilepath'}, { binmode => ':raw' });
        if (!$json) {
            warn "DB file $config{'DBFilepath'} is empty.\n";
            return;
        }
        %db = %{ decode_json $json };
        $dbKeysStart = scalar(keys(%db));
        print "INFO: $config{'DBFilepath'} has " . $dbKeysStart . " keys.\n";
    }
    elsif (!-e $config{'DBFilepath'}) {
        warn "INFO: NO DB file found at $config{'DBFilepath'}\n";
        exit;
    }
}

sub DirectoryListing {
    &Delimiter((caller(0))[3]);
    
    opendir(DIR, $config{'imageDir'});
    my @files = grep(/\.jpg$/,readdir(DIR));
    closedir(DIR);
    %data = map { $_ => { 'FILEPATH' => "$config{'imageDir'}$_" } } @files;
    # @hash{@keys} = undef;
}

sub Summary {
    &Delimiter((caller(0))[3]);
    
    print "$config{'DBFilepath'} has " . scalar(keys(%db)) . " keys (before $dbKeysStart).\n";
}

sub FindNewDataset {
    &Delimiter((caller(0))[3]);
    
    my $i = 0;
    for my $key (keys %data) {
        if (exists $db{$key}) {
            print "OLD: $key\n";
        }
        elsif (!exists $db{$key}) {
            print "NEW: $key\n";
            
            my $success = &uploadPHP($data{$key}{'FILEPATH'});
            if ($success) {
                print "success is $success\n";
                &AddToDB($key);
                &WipeData($key);
                last;
            }
        }
        $i++;
    }

    if ($i == scalar(keys(%data))) {
        warn "\nNO NEW FILES AVAILABLE.\n";
    }
}

sub uploadPHP {
    &Delimiter((caller(0))[3]);
    my $filepath = shift;
    my $success = 1;
    my $captionText = "$config{'uploadPHP_DESCRIPTION_ADD'}\n\n$config{'uploadPHP_TAGS'}";
    
    open PHPOUT, "$config{'uploadPHP_CMD'} $filepath \'$captionText\' $config{'uploadPHP'}{'USERNAME'} $config{'uploadPHP'}{'PASSWORD'} $config{'uploadPHP'}{'DEBUG'} $config{'uploadPHP'}{'TRUNCATED_DEBUG'} $config{'uploadPHP'}{'PROXY_USER'} $config{'uploadPHP'}{'PROXY_PASSWORD'} $config{'uploadPHP'}{'PROXY_IP'} $config{'uploadPHP'}{'PROXY_PORT'}|";
    while (<PHPOUT>) {
      print $_; # PRINT CURRENT PHP OUPUT LINE
      if ($_ =~ m/error/) {
          $success = 0;
      }
    }
    
    return $success;
}

sub WipeData {
    &Delimiter((caller(0))[3]);
    my $key = shift;
    
    print "Deleting $data{$key}{'FILEPATH'}...";
    unlink($data{$key}{'FILEPATH'}) or die "Could not delete $data{$key}{'FILEPATH'}!\n";
    print " Done.\n";
}

sub AddToDB {
    &Delimiter((caller(0))[3]);
    my $key = shift;
    
    $data{$key}{'TIMESTAMP_UPLOADED'} = &GetTimestamp('YMDHMS');
    $db{$key} = $data{$key};
    my $json = encode_json \%db;
    write_file($config{'DBFilepath'}, { binmode => ':raw' }, $json);
}

sub Delimiter {
    my $SubName = shift;
    print "\n" . "-" x 80 . "\nSUB " . $SubName . "\n" . '-' x 80 . "\n";
}

sub GetTimestamp {
    #&Delimiter((caller(0))[3]);
	my $switch = shift;
	
    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
    
    my $nice_timestamp;
    if ($switch eq 'YMDHMS') {
    	$nice_timestamp = sprintf ( "%04d%02d%02d_%02d%02d%02d", $year+1900,$mon+1,$mday,$hour,$min,$sec);
    }
    elsif ($switch eq 'YMD') {
    	$nice_timestamp = sprintf ( "%04d%02d%02d", $year+1900,$mon+1,$mday);
    }
    elsif ($switch eq 'year') {
    	$nice_timestamp = $year+1900;
    }
    elsif ($switch eq 'month') {
    	$nice_timestamp = $mon+10;
    }
    else {
    	print "Invalid/no switch detected. Use: 'YMDHMS' / 'YMD'\n";
    }
    
    return $nice_timestamp;
}