#!/usr/bin/perl -ws

#
# FindDSSSL
#
sub FindDSSSL($)
{
  my $sgml = shift;
  my $utils = $sgml . '/docbook/utils-0.6.9/docbook-utils.dsl';
  my $modular = $sgml . '/docbook/stylesheet/dsssl/modular';

  # RedHat 7.2 and 7.3
  my @redhat = ( $utils, $utils );

  # Debian 3.3r0
  my @debian = (
    $modular . '/html/docbook.dsl',
    $modular . '/print/docbook.dsl'
  );

  my @files = ( \@redhat, \@debian );

  for $files(@files)
  {
    return @$files if (-r $$files[0] && -r $$files[1]);
  }

  my $msg = "ERROR: Can't find DocBook DSSSL. Tried\n";
  for $files(@files) { $msg .= '  ' . $$files[0] . "\n"; }
  die $msg;
}

#
# main
#
die "Missing argument '-dsl'\n" if (!defined($::dsl) || $::dsl eq '');
my $tmp = $::dsl . '.tmp';
my $bak = $::dsl . '.bak';

my @file = FindDSSSL('/usr/share/sgml');

open(DSL, "<$::dsl") || die "ERROR: Can't open $::dsl for reading.";
open(TMP, ">$tmp") || die "ERROR: Can't open $tmp for writing.";

my $index;
LOOP: while(<DSL>)
{
     if (m/%html;/) { $index = 0; }
  elsif (m/%print;/) { $index = 1; }
  elsif (m/([^"]*)"[^"]*"\s*CDATA\s+dsssl\b(.*)/)
  {
    printf TMP "%s\"%s\" CDATA dsssl%s\n", $1, $file[$index], $2;
    next;
  }
  print TMP $_;
}
close TMP;
close DSL;

exit -1 if (!defined($index));

unlink $bak;
rename $::dsl, $bak;
rename $tmp, $::dsl;
