#!/usr/bin/perl
use Date::Manip;
use Image::ExifTool qw(:Public);
use Data::Dumper;
use File::stat;
use File::Copy;
use Time::localtime;
use strict;
use warnings;

my $src = "/media/bulk/digicam";
my $destination = "/media/bulk/digicam-hardlink";
chdir "$destination";

my $exifTool = new Image::ExifTool;
$exifTool->Options(DateFormat => "%c");

#&makelinks;
&deletedupes;
&perms;


sub makelinks {
my @list=`find $src -size -20M -a \( -iname "*.jpg" -o -iname "*.png" \)`;
chomp @list;
print "Creating hardlinks in $destination for all images in $src..."; 
foreach my $path (@list) {
    my $exifdate;
    my $info = $exifTool->ImageInfo($path);
    my %exif = %$info;
    $exifdate = $exif{'DateTimeOriginal'};
    if (! $exifdate) {
	$exifdate = ctime(stat($path)->mtime);
    }
    $exifdate = &ParseDate($exifdate);
    $exifdate = &UnixDate($exifdate,"%Y%m%dT%H%M%S");
    my $created = &UnixDate($exifdate,"%s");

    my @line = split("/",$path);
    my $length = @line;
    my $newname = join("~",@line[4 .. $length-1]);
    #my $newname = $line[-1];
    $newname =~ s/.JPG$/.jpg/;
    $newname =~ s/\ /_/g;
    my $output = "${exifdate}~${newname}";
    
    if (link("$path","${destination}/${output}")) {
	utime($created, $created, "${destination}/$output");
    }
    else {
	print "FAILED LINK: $path --> $output\n";
    }
}
print "DONE\n";
}

sub deletedupes {
print "Locating and deleting duplicate image files (log in $destination/dupes)...\n";
# Find duplicates using shell command
open(LOG, ">$destination/dupes");
print LOG "[File kept] other_duplicate other_duplicate\n";
open(DUPES, "fdupes -1 .|");
while (<DUPES>) {
    chomp;
    s/\.\///g;
    my @arr = split(" ");
    # Sorts first by number of letters, then numerically in reverse
    @arr = sort {$a =~ s/([a-z|-])/$1/gi <=> $b =~ s/([a-z|-])/$1/gi ||
		     $b cmp $a} @arr;
    my @counts;
    for my $name (@arr) {
	my $count = $name =~ s/([a-z|-])/$1/gi;
	push (@counts,$count);
    }
    # Find the index of the maximum element (or the largest index if tied)
    my $idxMax = 0;
    $counts[$idxMax] > $counts[$_] or $idxMax = $_ for 1 .. $#counts;
    # Remove the element with the largest count
    print LOG"[" . $arr[$idxMax] . "] ";
    delete $arr[$idxMax];
    # Delete the rest of the files
    print LOG join(" ",@arr);
    unlink @arr;
    print LOG "\n";
}
close(DUPES);
close(LOG);
print "DONE\n";
}

sub perms {
print "Changing permissions...";
qx(find . -type f -exec chmod 664 '{}' +);
qx(chown -R rde:home ./);
print "DONE\n";
}
