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

#
# FindDSL
#
sub FindDSL($@)
{
  my $ext = shift;

  my $msg = "ERROR: Can't find DocBook " . uc($ext) . ". Tried\n";
  for my $sgml(@_)
  {
    my $utils = "$sgml/docbook/utils-*/docbook-utils.$ext";
    my $style = "$sgml/docbook/$ext-stylesheets";
    my $raw = "$sgml/docbook/$ext/modular/";
    my $modular = "$sgml/docbook/stylesheet/$ext/modular";

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

    # XSL stylesheets on RedHat 7.3
    my @xsl = ( "$style/html/docbook.$ext", "$style/fo/docbook.$ext" );

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

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

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

    for my $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 my $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 = FindDSL 'dsl', '/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+dsl\b(.*)/)
  {
    printf TMP "%s\"%s\" CDATA dsl%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;
