#!/usr/bin/perl
# run a script on every file on the command line, piping it to a different folder and the same name.txt
# Jerry Stratton astoundingscripts.com
use File::Basename;

while ($option = shift) {
	if ($option eq '--help') {
		help();
	} elsif ($option eq '--commit') {
		$commit = 1;
	} elsif (-d $option) {
		help("Two directories specified ($outputDirectory:$option)") if $outputDirectory;
		$outputDirectory = $option;
	} elsif (-f $option) {
		$files[$#files+1] = $option;
	} elsif (`which $option`) {
		help("Two scripts specified ($script:$option)") if $script;
		$script = $option;
	} else {
		help("Unknown option $option");
	}
}

help('No output directory specified') if !$outputDirectory;
help('No script specified') if !$script;
help('No files specified') if !@files;

foreach $source (@files) {
	($sourceName, $folder, $extension) = fileparse($source, qr/\.[^.]+/);
	$outputPath = "$outputDirectory/$sourceName.txt";
	next if -f $outputPath && -M $source >= -M $outputPath;

	$source = quotemeta($source);
	$outputPath = quotemeta($outputPath);
	$command = "$script $source > $outputPath";
	if ($commit) {
		print `$command`;
	} else {
		print "$command\n";
	}
}

sub help {
	my $message = shift;

	print "$0 [--help] [--commit] <outputDir> <script> <filename> [filenames]\n";
	print "Run <script> on every <filename>, piping output to <outDir> as a .txt file.\n";
	print "\t--help:\tthis help text.\n";
	print "\t--commit:\tperform script.\n";
	print "\toutputDir:\tthe directory to pipe output to, using the source file's filename.txt.\n";
	print "\tscript:\tthe script to run on each file, whose output is piped.\n";
	print "\tfilenames:\tthe filenames to run the script on, and whose name produces the output filename with .txt as the extension.\n";

	print "\n$message.\n" if $message;

	exit;
}
