#!/usr/bin/perl
###################### Copyright notice ##################################
#       (c) 2000-2003 Thierry Vignaud <tvignaud@mandrakesoft.com>, MandrakeSoft.
#       This soft is released under the GNU GPL (see http://ww.gnu.org for further
#       information)
#



use MDK::Common;

die "Usage: $0 LOCALE_2CHARS_ISO_CODE LANGUAGE_NAME\nDefault format is \"html\".\n" if @ARGV ne 2;

my ($LANG, $lang_string) = @ARGV;

# Meta information can be included: one line per one commandline argument
my %metas = (
             sl => '<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-2">',
            );


system(join(';', "find -type d | xargs chmod 755; find -type f | xargs chmod 644", if_(glob("howto-html-??"), "mv howto-html-??/* .; rmdir howto-html-??/")));

# Handle both html/ directored tarballs and othere
system("mv html/* .; rmdir html") if -d 'html';

my $howtos = { main => [], mini => [] };


# This infrastructure enable to skip REDIRECT links below:
foreach my $top (qw(. mini)) {
    # For both howtos and mini-howtos:
  LOOP: foreach my $dir (glob("$top/*/")) {
        chop $dir;
        # For each directory, try to lookup index.html, <howto>-HOWTO.html or <howto>.html
        if (-e "$dir/index.html") {
            push @{$howtos->{howtos}}, "$dir/index.html";
        } else {
            foreach my $master (glob("$dir/*-HOWTO.html")) {
                push @{$howtos->{howtos}}, $master;
                next LOOP;
            }
            my $idx = $dir;
            $idx =~ s!-html/!.html!g;
            $idx =~ s!.*/!!g;
            foreach my $index ("$dir/$idx", "$dir/$idx.html", "$dir/t2.html", glob("$dir/*-HOWTO-??.html")) {
			 push @{$howtos->{howtos}}, $index if -e $index;
            }
        }
    }
}


system("rm -f .html");

# Page header (from LN)
print qq(<HTML><HEAD>
$metas{$LANG}
<TITLE>$lang_string HOWTOs and mini-HOWTOs</TITLE>
<!-- Index.html for "$lang_string" Howtos & mini-Howtos -->
<!-- Copyright 2000-2003 Thierry Vignaud <tvignaud\@mandrakesoft.com>, MandrakeSoft -->
<!-- Distribuable under terms of GPL Licence -->
</HEAD>
<BODY BGCOLOR=WHITE>
<FONT face="Verdana, Arial, Helvetica, sans-serif" size="2">

<TABLE BORDER="0"><TR><TD  colspan="2">
<TR><TD WIDTH="11%" BGCOLOR="#FFFFFF">
<TD WIDTH="89%" BGCOLOR="#FFFFFF">
<H1><font face="Verdana, Arial, Helvetica, sans-serif" size="2"> 
<font size="5" color="#21449c">$lang_string HOWTOs and mini-HOWTOs</font></font></h1>
<TR><td width="11%" bgcolor="#7983BC">&nbsp;</td>
<td width="89%">
<UL>
);



sub output_links_from_list {
    my ($howtos) = @_;
    foreach my $title (sort keys %$howtos) {
        print "<LI><A HREF=\"$$howtos{$title}\">$title</A>\n";
    }
}

my %classes = (
               accessibility => ["Accessibility:", 'accessibility|emacspeak'],
               boot => [ "Bootstrapping:", 'Bootprompt|Bootdisk|Clone|Diskless|From-PowerUp|GRUB|LILO|MILO|Remote-boot|SRM' ],
               clusters => [ "Clustering and Parallel processing:", 'Beowulf|OpenMOSIX|Parallel-proces|SSI-UML|SMP' ],
               cpu => [ "CPU design:", 'Alpha|CPU-' ],
               db => [ "Databases:", 'DB2|IngresII|Oracle|Postgres|SQL|Sybase' ],
               fs => [ "FileSystems:", 'Ext2fs|Filesystem|Partition|Quota|UMSDOS|Swap-space|\+XFS' ],
               games => [ "Games:", 'Game-server|Gamers|Quake' ],
               gen_doc => [ "Generic Linux Documentation:", 'HOWTO(/|-INDEX)|INFO-SHEET|LDP-review|Linuxdoc|man-page|META-FAQ|Reading-list|Tips|WikiText' ],
               hardware => [ "Hardware:", '3dfx|Busmouse|BTTV|CDROM|CD-writ|Hardware(/|-[^R])|IR-HOWTO|K7s5a|keyboard|PCI|Plug-and-Play|print|Smart-card|Ultra-DMA|Zip[^2]' ],
               kernel => [ "Kernel internals:", 'IO-perf|Kernel|Module|SCSI-(2.4|SCSI-generic)' ],
               l10n => [ "International:", 'Belarusian|Belgian|Chinese|Danish|Esperanto|Francophones|French|German|Hebrew|Hellenic|Indic|Italian|Latvian|Polish|Portuguese|Serbian|Slovak|Slovenian|Spanish|Thai|Turkish' ],
               install => [ "Installation:", 'CD-distr|Debian-jigdo|Install|Kickstart|Redhat-CD|RPM|Software-build|Update|Upgrade' ],
               laptops => [ "Laptops and PDA:", 'Battery-powered|Handspring-visor|Laptop|Palm|PCMCIA|Psion|VAIO|Wearable|Wireless' ],
               linux_on_architecures => [ "Linux on specific architectures:", 'IBM7248|Linux-Init|PA-RISC|MIPS-|SPARC' ],
               mail_clients => [ "Mail clients:", 'Pine|TkRat' ],
               multimedia => [ "Multimedia:", 'CDserver|DVD-|MP3|VideoLAN' ],
               net => [ "Network:", 'ARP|ATM-linux|Automount|AX25|Bandwidth|Bridge|call-back|DHCP|Dial|Divert-socket|DNS|Domain|DSL|Fax|Firewall|FTP|IMAP|IP(-|CH|v6|X)|IRC|ISP|LDAP|Leased-Line|mail|Masq|Modem|Multicast|NCD|NET|news|NFS|NIS|PLIP|PPP|Remote-bridging|routing|Samba|SMB|Serial-Lap|Token-Ring|TransparentProxy|Virtual-services|VPN|UUCP' ],
               office => [ "Office:", 'Bangla|docbook|emacs|Euro-char|Font|StarOffice|tetex|vim|wordperfect' ],
               os => [ "OSes cohabitation:", 'FreeBSD|MultiOS|NT-Loader|OS2|Solaris|Windows|WinNT|Win9' ],
               programming => [ "Programming:", 'AI-alife|Assembly|Bash-prog|Beautifier|-dlopen|GCC|Software-Proj-Mgmt|highquality-apps|Lex-Yacc|IO-port|Java|Multi-distro-dev|Ncurses-prog|Program-Libra|RCS|Serial-prog|Software-rel|TclTk|valgrind' ],
               security => [ "Security:", 'chroot-bind|Compressed-TCP|mindterm-ssh|mutt-gnupg|secure-(prog|pop)|SSL-certif|ssl-redhat|security|shadow|User-auth' ],
               servers => [ "Servers:", 'Apache|Caudium|Majordomo|Postfix|Virtual-Web|WWW' ],
               sound => [ "Sound:", 'ALSA|MIDI|Sound' ],
               stockage => [ "Stockage:", 'ftape|Hard-disk|[^V]IDE|Large-disk|LVM|JAZ|Multi-disk|Optical|RAID' ],
               transfuge => [ "Migration:", 'Win-to|VMS-to' ],
               x11 => [ "X Window:", '3-button|3D-model|FDU|i810|intkeyb|LBX|Nvidia-opengl|TT-Debian|Wacom|X11|XDM|X-app|X-Big|XFree|Xinerama|xterm|X-Term|XWindow' ],
               zother => [ "Other howtos:", '' ],
               );

sub extract_titles_and_output_links_from_list {
    my (@list) = @_;
    return unless @list;
    # Skip REDIRECT links (see above why)
    my @HOWTOS_LIST = map { chomp; $_ } `fgrep -L \"<TITLE>REDIRECT</TITLE>\" @list`;

    # Determine the title
    my %howtos = map {
        my $file = $_;
        # Get rid of duplicate item names for different (subsequent) links
        my $TITLE;
        # Be aware of .dsc if needed, else "regexipy" the index
        if (-s "$file.dsc") {
            $TITLE=cat_("$file.dsc");
        } else {
            local *F;
            open F, $file;
            while (<F>) {
                # Detect badly generated howto indexes:
                if (m@<(TITLE|title)>(.*)</(TITLE|title)>@) {
                    $TITLE = $2;
                    last;
                } elsif (/^><(TITLE|title)$/) {
                    $_ = <F>;
                    # Handle badly generated howto indexes:
                    if (m@^>(.*)</(TITLE|title)@) {
                        $TITLE = $1;
                        last;
                    }
                }
            }
        }
        unless ($TITLE) {
            $TITLE ||= "\"$file\"";
            $TITLE =~ s/\.html//;
            #$TITLE =~ s/.*\///;
        }
        $TITLE =~ s/<[^>]*>//g;
        $TITLE =~ s!\n!!;
        $TITLE => $file;
    } @HOWTOS_LIST;
    foreach my $class (sort keys %classes) {
        my ($name, $regexp) = @{$classes{$class}};
        my %sub_howtos;
        while (my ($title, $file) = each %howtos) {
            if ($file =~ /$regexp/i) {
                $sub_howtos{$title} = $file;
                delete $howtos{$title};
            }
        }
        if (!is_empty_hash_ref(\%sub_howtos)) {
            print "<LI>$name\n<UL>";
            output_links_from_list(\%sub_howtos);
            print "</UL><HR>\n";
        }
    }
    output_links_from_list(\%howtos);
}

extract_titles_and_output_links_from_list(@{$howtos->{howtos}}, glob("[A-Z]*.html"), glob("mini/[A-Z]*.html"));


# Page Footer (from LN)
print qq(
</UL></TABLE>
</FONT>
</BODY></HTML>
);
exit 0;
