#!/usr/bin/perl -w
#
# Create a file which describes dependencies. The file gets included by the
# Makefile which creates TOC.lyx files 
#
# Essentially, this file creates a TOCs target, which makes the
# TOC.lyx for every possible language. Then it creates a target for
# each language's xx_TOC.lyx, which depends on various files.
# E.g., de_TOC.lyx depends on files like de_UserGuide.lyx. If non-English
# files don't exist, TOC.lyx just uses the corresponding English file.

use strict;

print <<ENDHEAD;
# This is a Makefile for the TOC.lyx files.
# It was automatically generated by $0
#
# First come the rules for each xx_TOC.lyx file. Then comes the
# TOCs target, which prints all the TOC files.
ENDHEAD

# Add (whitespace separated) "Foo" to this list to create a TOC for Foo.lyx
# Don't bother including Reference.lyx
my @Default_Files = map {"$_.lyx"} qw(
    Intro FAQ Tutorial UserGuide Extended Customization
);

my $Toc_Top_Dir = "TOC_top";
my $Toc_Top_Base = "TOC_top.lyx";
my $Toc_Base = "TOC.lyx";

# Any language which has any translated docs needs to have a TOC.lyx
my %a;
opendir (DIR, ".") or die $!;
foreach (readdir DIR) {
    $a{$1}++ if /^([a-z]{2}_)/;
}
close DIR;
my @langs = sort keys %a;
unshift @langs, ""; # English file doesn't have en_ prefix

# Foreach language, create Makefile dependencies
# and create make action
my @Tocs; # List of all TOC files
my $lang;
foreach $lang (@langs) {
    # "TOCs" target will depend on this language's TOC
    my $tfile = "$lang$Toc_Base";
    push @Tocs, $tfile;

    # Make list of files, English or not.
    # First TOC_Top file
    # TODO print warning if language-specific file doesn't exist?
    my $ttfile = (-e "$Toc_Top_Dir/$lang$Toc_Top_Base" ? 
	"$Toc_Top_Dir/$lang$Toc_Top_Base" :
	"$Toc_Top_Dir/$Toc_Top_Base");
    my @Files = ($ttfile);

    # Now actual Doc files
    foreach (@Default_Files) {
	my $i18n = $lang . $_;
	# Use xx_foo if it exists, else foo
        push (@Files, (-e $i18n ? $i18n : $_));
    }

    # Create Makefile dependencies for this language's TOC file
    my $depend = "$tfile: ";
    $depend .= join (" ", @Files);
    print "$depend\n";

    # Create make action
    my $make = "\tperl Doc_toc.pl ";
    # TODO is there a simple way to tell it to pass all the dependencies in?
    # Then this could be a default rule for creating *TOC.lyx!
    $make .= join (" ", @Files);
    $make .= ' > $@';
    print "$make\n\n";
}

my $depend = "TOCs: ";
$depend .= join (" ", @Tocs);
print "#" x 80,"\n";
print "\n$depend\n";
print "\t\@echo Made TOCs succesfully.\n";
