#!/usr/bin/perl
# Copyright(c) René Wagner 2019-2020
# published under BSD 3-Clause License
# https://www.codewolke.net/photo-helpers/

use warnings;
use strict;
use feature qw(say);
use Cwd;
use File::Basename;
use File::Find::Rule;
use File::Find;
use File::Spec::Functions;
use Getopt::Std;

$Getopt::Std::STANDARD_HELP_VERSION = 'true';

my $VERSION = '0.3';
my $PROGRAM = 'Orphaned Sidecar Cleaner';

# read commandline switches
our $opt_d = 0;

if ( !getopts('d') )
{
	die("Invalid parameters provided! See 'silkypix_multiversion_sidecar_cleaner.pl --help' for more details.");
}

# read remaining commandline args
# last dir will win
my $work_dir = getcwd;
foreach my $arg ( @ARGV ) 
{
	if ( -d $arg ) { $work_dir = $arg }
}

delete_files($work_dir, $opt_d);

exit 0;

sub delete_files
{
	my ( $delete_dir, $delete_flag ) = @_;
	my ( $file_counter ) = 0;

	say "working directory: $delete_dir";
	say 'action           : '. ($delete_flag ? 'delete' : 'list only') ."\r\n";
	say 'files with missing raw:';

	# alle Dateien in allen Unterordnern *.spd *.spf suchen
	my @files = File::Find::Rule->file->name( qr/\.sp(d|f)$/i )->in( $delete_dir );
	
	foreach my $file ( @files )
	{
		if ( ! exists_raw_filename($file) )
		{
			print $file .'...';
			$file_counter++;
			if ( $delete_flag )
			{
				if ( unlink $file )
				{
					print 'deleted.';
				}
				else
				{
					print " deletion failed: $!";
				} 
			}
			say '';
		}
	}
	
	say "\r\n$file_counter orphaned sidecar files found.";
}

sub exists_raw_filename
{
	my ( $original_file ) = @_;
	
	my ( $filename, $dirs ) = fileparse($original_file);
	# Silkypix Sidecar files reside in a "SILKYPIX_DS" folder, so we need to search in the parent folder
	$filename =~ s/\.\d+\.sp.$//g;
	if ( -f catfile(dirname($dirs), $filename) )
	{
		return 1;
	}
	return 0;
}

sub main::VERSION_MESSAGE()
{
	say $PROGRAM . ' - version ' . $VERSION;
	say 'published under BSD 3 - Clause License';
	say 'Copyright(c) 2019-2020 René Wagner';
	say 'https://www.codewolke.net/photo-helpers/';
}

sub main::HELP_MESSAGE
{
	say '';
	say 'Deletes Silkypix Sidecar files when corresponding RAW files are missing.';
	say '';
	say 'commandline parameters:';
	say 'orphaned_sidecar_cleaner.pl - list orphaned sidecar file in current working directory and subfolders';
	say 'orphaned_sidecar_cleaner.pl -d - delete orphaned sidecar file in current working directory and subfolders';	
	say 'orphaned_sidecar_cleaner.pl <folder> - list orphaned sidecar file in given directory and subfolders';
	say 'orphaned_sidecar_cleaner.pl -d <folder> - delete orphaned sidecar file in given directory and subfolders';
	say 'orphaned_sidecar_cleaner.pl --help - show this help';
}