#!/bin/perl -w
# $Id: mkconf,v 2.10 1998/11/11 05:47:03 hasegawa Exp $
# copyright (c)1997-1998 Yoshinori Hasegawa <hasegawa@madoka.org>

&main(@ARGV);

sub main {
  local(@args) = @_;
  local($dir);
  if (!@args) {
    &usage();
    exit(1);
  }
  $dir = shift(@args);
  &property("$dir/plum", 'plum');
  print "\n";
  &traverse("$dir/module", '');
}

sub traverse {
  local($base, $dir) = @_;
  local(@files, $file, $prop);
  opendir(DIR, "$base/$dir") || die;
  @files = readdir(DIR);
  closedir(DIR);
  foreach $file (sort(@files)) {
    next if $file =~ /^\./;
    next if $file eq 'SCCS';
    next if $file eq 'RCS';
    next if $file eq 'CVS';
    next if $file =~ /\,v$/;
    if (-d "$base/$dir/$file") {
      if ($dir) {
        &traverse($base, "$dir/$file");
      } else {
        &traverse($base, $file);
      }
    } elsif ($file =~ /\.plm/) {
      $prop = "$dir.$`";
      $prop =~ tr/\//\./;
      if ($dir) {
        print "- $dir/$file\n";
        &property("$base/$dir/$file", $prop);
      } else {
        print "- $file\n";
        &property("$base/$file", $prop);
      }
      print "\n";
    }
  }
}

sub property {
  local($file, $prop) = @_;
  local(@prog, @doc);
  @prog = ();
  @doc = ();
  if (open(FILE, $file)) {
    while (defined($line = <FILE>)) {
      $line =~ tr/\r\n//d;
      while ($line =~ /\&\'property\(.*\,\s*\'([^\']*)\'\)/) {
        push(@prog, "# $prop.$1: ");
        $line = $';
      }
      last if $line eq '__END__';
    }
    while (defined($line = <FILE>)) {
      $line =~ tr/\r\n//d;
      if ($line =~ /^\s*\<DT\>\s+([\w\.]+)/) {
        push(@doc, "# $1: ");
      }
    }
    close(FILE);
  }
  foreach $doc (@doc) {
    print $doc, "\n";
    @prog = grep($_ ne $doc, @prog);
  }
  $last = '';
  foreach $prog (sort(@prog)) {
    print '# ', $prog, "\n" if $prog ne $last;
    $last = $prog;
  }
}

sub usage {
  print 'usage: perl mkconf <plum-top-directory>', "\n";
}
