#!/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::Copy;
use File::Find;
use File::Find::Rule;
use File::Spec::Functions;
use Getopt::Std;

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

my $VERSION = '0.5';
my $PROGRAM = 'JpegDivider';

# read commandline switches
our $opt_m = 0;
our $opt_f = 'JPEG';

if ( !getopts('mf:') )
{
	die("Invalid parameters provided! See 'jpegdivider.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 }
}

move_files($work_dir, $opt_m);

exit 0;

sub move_files
{
	my ( $dir, $move_flag ) = @_;
	my $move_counter = 0;

	say "working directory: $dir";
	say 'action           : '. ($move_flag ? 'move' : 'list only');
	say "subfolder        : $opt_f";
	say '';
	
	my $destination_dir = catdir($dir, $opt_f);
	if ( $move_flag && ! -d $destination_dir )
	{
		mkdir $destination_dir or die "Could not create destination dir $_ : $!";
	}
	
	my @files = File::Find::Rule->file()->name( qr/\.jpe{0,1}g$/i )->maxdepth(1)->in( $dir );
	
	foreach my $file ( @files )
	{
		print $file .'...';
		$move_counter++;
		if ( $move_flag )
		{
			if ( move($file, catfile($destination_dir, basename($file)) ) )
			{ 
				print "moved.";
			}
			else
			{
				print "move failed: $!";
			}
		}
		say '';
	}
	
	say "\r\nfound $move_counter jpeg files to subfolder.";
}

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 'Moves JPEG files to a designated subfolder, by default "JPEG"';
	say '';
	say 'commandline parameters:';
	say 'jpegdivider.pl - list all jpeg files in the current working dir';
	say 'jpegdivider.pl -m - create a subfolder "JPEG" in the current working dir and move jpeg files in there';
	say 'jpegdivider.pl <folder> - list all jpeg files in the given directory';
	say 'jpegdivider.pl -m <folder> - create a subfolder "JPEG" in the given directory and move jpeg files in there';
	say 'jpegdivider.pl --help - show this help';
}