#!/usr/bin/perl -w

use strict;

sub Usage($$) {
    my $code = shift;
    my $str = shift;

    my $name = $0;
    $name =~ s|.*/||;
    my $instr =
"Usage:
	$name [-m] [-dx] [-h] [-t] <pattern> <arg>...
Where:
	modify '<arg>...' using <pattern>, and print or run the result

	-r execute the resulting line as a command line, using the first <arg> a command
	-m print a makefile dependancy line (<pattern>: <arg>...)
	-d use \"x\" as a <delimiter> instead of \",\"
	-h print this usage text

	<pattern> a <delimiter> separated pattern
	<arg>... arguments, possibly modified according to <pattern>

	text from <pattern> is be substituted in the <arg>'s using the syntax %0, %1, etc
	%0 etc, are derived like:
	  %0 is the unmodified <pattern>
	  strip <pattern> of any extention (e.g. requiem,cb,12.ly -> requiem,cb,12)
	  split it at the delimiter (e.g. requiem,cb,12 -> %1 = requiem, %2 = cb, %3 = 12, %4 and higher are empty )
	  apply it to the <arg>'s (e.g. %1.ily -> cb.ily)
Example:
	below %1 = requiem, %2 = cb, and %3 = 12
	(you need to escape > on the -r line below, to make the redirection happen _after_ %0 is substituted)

	\$ $name -r requiem,cbn,12.ly 'cat ../include/%2.ily <(echo \"#(set-global-staff-size %3)\") %1.ly > %0'
	\$ cat requiem,cbn,12.ly
	% choirbook format, narrow margins
	\\version \"2.19.0\"
	\\paper {
	    paper-width = 190 \\mm
	    paper-height = 270 \\mm

	    left-margin = 10 \\mm
	    line-width = 163 \\mm

	    ragged-bottom = ##t
	    indent = 10.0\\mm
	}

	\\header {
	  tagline = \"\"
	}
	#(set-global-staff-size 12)
	...
	\$ $name -m requiem,cbn,12.ly %2.ily %1.ly
	requiem,cbn,12.ly:	cbn.ily requiem.ly
	\$
";

    if ($code) {
	print STDERR $str if $str;
    } else {
	print $str if $str;
    }
    print $instr;
    exit($code);
}

sub main() {
    my $dep = 0;
    my $del = ",";
    my $run = 0;

    while (@ARGV && $ARGV[0] =~ /^-/) {
	my $opt = shift @ARGV;
	if ($opt eq '-h') {
	    Usage(0, "");
	} elsif ($opt eq '-m') {
	    $dep = 1;
	} elsif ($opt eq '-r') {
	    $run = 1;
	} elsif ($opt =~ /^-d(.)$/) {
	    $del = $1;
	} else {
	    Usage(1, "unknown option <$opt>\n");
	}
    }
    if (@ARGV < 2) {
	Usage(1, "<pattern>, and/or <arg>'s\n");
    }
    my $pattern = shift @ARGV;
    my $stem = $pattern;
    $stem =~ s/\.[^.]+$//;
    my @fld = split(/$del/, $stem);
    unshift @fld, $pattern;

    for my $k (@ARGV) {
	$k =~ s/(^|[^%])%(\d+)/$2 < @fld ? "$1$fld[$2]" : "$1"/ge;
    }
    my $arg_list = join(" ", @ARGV);
    if ($dep) {
	print "$pattern:\t$arg_list\n";
    } else {
	if ($run) {
	    my $sh = "/bin/sh";
	    if (-x "/bin/bash") {
		# you need bash if you want to do something like (i.e. using the <(...) operation)
		# rewrite.pl -r  requiem,cb,12.ly 'cat <(echo "#(set-global-staff-size %3)")'
		$sh = "/bin/bash";
	    }
	    open(FH, "| $sh") || die("Cannot start $sh");
	    $arg_list .= "\n";
	    print FH $arg_list;
	    close(FH);
	} else {
	    print "$arg_list\n";
	}
    }
}

main();
