#!/usr/bin/perl -ws

#
# FindDSSSL
#
sub FindDSSSL(@)
{
  my $msg = "ERROR: Can't find DocBook DSSSL. Tried\n";
  for my $sgml(@_)
  {
    my $utils = $sgml . '/docbook/utils-*/docbook-utils.dsl';
    my $raw = $sgml . '/docbook/dsssl/modular/';
    my $modular = $sgml . '/docbook/stylesheet/dsssl/modular';

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

    # FreeBSD-4.6.1
    my @freebsd = (
      $raw . '/html/docbook.dsl',
      $raw . '/print/docbook.dsl'
    );

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

    my @pattern = ( \@redhat, \@debian, \@freebsd );

    for $pattern(@pattern)
    {
      my @html = glob($$pattern[0]);
      my @print = glob($$pattern[1]);
      next if ($#html < 0 || $#print < 0);

      return ( $html[0], $print[0] ) if (-r $html[0] && -r $print[0]);
    }
    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', '/usr/local/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;
