#!/usr/bin/perl -w
# this program sucks and is a total hack and needs TONS of work... 
#
use Cwd;
use Getopt::Long;
use strict;


sub showUsage {
	print "\n";
	print "usage:\n";
	print "  eren <options> <replace regex>\n\n";
	print "  where <options> can be:\n";
	print "  --filter <filemask regex>  : only apply to files matching filter\n";
	print "                             : (default tries ALL files)\n";
	print "  --preview                  : don't change files, just preview\n";
	print "  --help                     : this help\n\n";
	print "examples:\n\n";
	print "  eren -f \"/\\.jpg/\" \"/\\.jpg/\\.gif/\" -p\n";
	print "  eren \"/car/fastcar/\n";
}# showUsage

my ($filefilter, $preview, $replacestr, $help) = ("/.*/", 0, undef, 0);

my $result = GetOptions("filter=s" => \$filefilter,
						"preview" => \$preview,
						"help", => \$help);

if(($#ARGV != 0) or $help){
	showUsage() and exit;
}

# Reformatting of the replace string
if($#ARGV == 0){
	$replacestr = $ARGV[0];
}
if(not $replacestr =~ /.+\/.+/){
	$replacestr = undef;
}
else{
	(not $replacestr =~ /^\//) and $replacestr = "/" . $replacestr;
	if(not ($replacestr =~ /^\/.*\/.*\/\w+/)){
		(not $replacestr =~ /\/$/) and $replacestr = $replacestr . "/";
		# TODO: Could probably use more reformatting (parens? etc)
	}
}

# Reformatting the file filter
if($filefilter){
	$filefilter =~ s/^\///;	# remove leading slash
	$filefilter =~ s/\/$//; # remove trailing slash
}

if(!$replacestr){
	showUsage() and exit;
}

my $root = getcwd;
if ( not $root =~ /\^/){
	#$root .= "\\";
	$root .= "/";
}
chdir($root);

opendir(DIRH, $root) or die "Error opening directory: $root";

my @files = grep { $_ ne '.' and $_ ne '..' } readdir DIRH;

closedir DIRH;
my $matchct = 0;

foreach my $file (@files){
	next if -d($root . $file);
	
	next if (($preview) and not ($file =~ /$filefilter/));
	@_ = split /\//, $replacestr;
	my $icase = '';
	($_[3] =~ /i/) and $icase = 'i';
	my $cmd = sprintf("\$file =~ /%s/%s;", $_[1], $icase);
	
	next if not eval $cmd;
	
	$preview and print "PREVIEW: ";
	$matchct++;
	
	my $oldfile = $file;
	print "$oldfile --> ";
	$file =~ eval " \$file =~ s$replacestr;";
	print "$file\n";
	$preview and next;
	rename($root . $oldfile, $root . $file) or print "Failed to rename $root$oldfile\n";
}

not $matchct and print "No files matched given criteria.\n";
