#!/usr/bin/perl -w
use strict;

=head1 NAME

xslt.pl - wrapper to unify command-line syntax of xslt command-line processors

=head1 DESCRIPTION 

The different processors vary in argument order, quoting of params, etc.

xsltproc [options] stylesheet file [file ...]
         --output file or -o file: save to a given file
        --param name value : pass a (parameter,value) pair (string values are quoted)
        --stringparam name value : pass a (parameter, UTF8 string value) pair

sabcmd [options] <stylesheet> [<input> [<output>]] [assignments]
       assignments are like: $var=val with no quotes

java net.sf.saxon.Transform [options] input stylesheet [params]

=cut

my $PROC = $ENV{XSLTPROC} || 'sablotron';
# my $PROC = 'saxon6';
# my $PROC = 'xsltproc';

my $CMDS = {
    saxon6 => 'java',
    saxon8 => 'java',
    xsltproc => 'xsltproc',
    sablotron => '/usr/local/bin/sabcmd.hide',
};
my $CMD = $CMDS->{$PROC} || die "unknown xslt processor PROC=$PROC";

my $EXTRAS = {
    saxon8 => ['-cp', '/usr/share/java/saxon8.jar', 'net.sf.saxon.Transform'],
    saxon6 => ['-cp', '/usr/share/java/saxon.jar', 'com.icl.saxon.StyleSheet'],
};

sub sablotron {
    my @args;
    if ($PROC eq 'sablotron') {
	@args = @ARGV;
    }
    elsif (scalar(@ARGV) < 2) {
	@args = @ARGV;
    }
    else {
	my $stylesheet = shift @ARGV;
	my $input = shift @ARGV;
	my $output;
	my @params = ();
	my @options = ();
	while(my $arg = shift @ARGV) {
	    if ($arg =~ m/\$(.*)=(.*)/) {
		my ($var,$val) = ($1,$2);
		push(@params, '--param', $var, "'$val'") if $PROC eq 'xsltproc';
		push(@params, "$var='$val'") if $PROC =~ 'saxon';
	    }
	    elsif (!$output) {
		$output = $arg;
		push(@options, '--output', $output) if $PROC eq 'xsltproc';
		push(@options, '-o', $output) if $PROC =~ 'saxon';
	    }
	    else {die "arg '$arg' no supported";}
	}
	@args = (@options, @params, $stylesheet, $input) if $PROC eq 'xsltproc';
	@args = (@options, $input, $stylesheet, @params) if $PROC =~ 'saxon';
    }
    my $extras = $EXTRAS->{$PROC};
    if ($extras) {@args = (@$extras, @args);}
    print STDERR $CMD, ' ', join(' ',@args), "\n";
    exec $CMD, @args;
}

if ($0 =~ 'sabcmd') {
    sablotron();
}
die "no match to program '$0'";
 
