#!/usr/bin/perl
###################### Copyright notice ##################################
#       (c) 2000-2004 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 qq(Usage: $0 LOCALE_2CHARS_ISO_CODE LANGUAGE_NAME\nDefault format is "html".\n) if @ARGV != 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 { uc($a) cmp uc($b) } keys %$howtos) {
        print qq(<LI><A HREF="$howtos->{$title}">$title</A>\n);
    }
}

my %classes = (
               accessibility => [ "Accessibility:", 'accessibility|emacspeak' ],
               advocacy => [ "Advocacy:", 'Advocacy|Commercial-Port-Advocacy|Encourage-Women-Linux' ],
               backup => [ "Backups:", 'ADSM|Backup-With-MSDOS|Linux-Complete-Backup-and-Recovery' ],
               bench => [ "Benchmarking:", 'Benchmarking|BogoMips' ],
               boot => [ "Bootstrapping:", 'Bootprompt|Bootdisk|Clone|From-PowerUp|[^-]LILO|LILO-crash|Linux-i386-Boot-Code|Loopback-Root-FS|MILO|SRM' ],
               netboot => [ "Network bootstrapping:", 'Diskless|Network-boot|Diskless-root-NFS-other|NFS-Root|Remote-boot' ],
               multiboot => [ "Multiboot:", 'Linux\+Win9x\+Grub|Multiboot-with-GRUB|Multiboot-with-LILO' ],
               clusters => [ "Clustering and Parallel processing:", 'Beowulf|Cluster|OpenMOSIX|Parallel-proces|SSI-UML|SMP' ],
               communauty => [ "Communauty and services:", 'Commercial|Entrepreneur|Online-Troubleshooting|User-Group|VAR' ],
               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' ],
               input => [ "Input hardware:", '3-Button|Busmouse|XFree86-Touch|XFree86-Second-Mouse|Wacom' ],
               graphic => [ "Grahical hardware:", '3dfx|i810|Nvidia-opengl|XFree86-R200' ],
               hardware => [ "Hardware:", 'Boca|BTTV|CDROM|CD-writ|Compaq-T1500|GTEK-BBS-550|Hardware(/|-[^R])|Home-Electrical-Control|HP|Infrared|IR-HOWTO|K7s5a|keyboard|PCI|Plug-and-Play|Smart-card|Ultra-DMA|Zip[^2]' ],
               kernel => [ "Kernel internals:", 'IO-perf|Kernel|Module|SCSI-(2.4|generic|Generic|Programming)' ],
               l10n => [ "International:", 'Belarusian|Belgian|Chinese|Danish|Esperanto|Francophones|Finnish|French|German|Hebrew|Hellenic|Indic|Intkeyb|Italian|Latvian|Polish|Portuguese|Serbian|Slovak|Slovenian|Spanish|Tamil-Linux|Thai|Turkish|Unicode' ],
               install => [ "Installation:", 'CD-distr|Compaq-Remote-Insight-Board|Debian-jigdo|Install|Kickstart|Redhat-CD|Update|Upgrade' ],
               kiosk => [ "Kiosk:", 'Kiosk' ],
               laptops => [ "Laptops and PDA:", 'Handspring-visor|Laptop|Palm|PCMCIA|Psion|VAIO|Wearable|Wireless' ],
               power => [ "Power saving:", 'ACPI|Athlon-Powersaving|Battery-powered|UPS' ],
               linux_on_architecures => [ "Linux on specific architectures:", 'IBM7248|Linux-Init|PA-RISC|MIPS-|SPARC|VME' ],
               mail_clients => [ "Mail clients:", 'Mail-User|Offline-Mailing|Pine|TkRat' ],
               multimedia => [ "Multimedia:", 'CDserver|DVD-|Kodak-Digitalcam|MP3|Scanner|USB-Digital-Camera|VCR|VideoLAN' ],
               net_cnx => [ "Network connection:", 'ACP-Modem|BTI-PPP|Cable-Modem|call-back|Conexant\+Rockwell-modem|DSL|IP-Alias|ISP|Linksys-Blue-Box-Router|Linmodem|/Modem/|Modems|Motorola-Surfboard-Modem|Pager|PCTel-MicroModem-Config|PPP|Winmodems-and-Linux' ],
               net_concepts => [ "Network concepts:", 'Unix-and-Internet-Fundamentals' ],
               net_vpn => [ "VPN:", 'Cipe\+Masq|ppp-ssh|VPN' ],
               net => [ "Network:", 'ARP|ATM-linux|Automount|AX25|Bandwidth|Bridge|DHCP|Dial|Divert-socket|Domain|FBB|FTP|IMAP|IP-Masquerade|IPMasquerading\+Napster|LDAP|Leased-Line|Linux-Modem-Sharing|Masquerading-Simple|Modem-Dialup-NT|Multicast|NCD|NET|news|[^-]NFS[^-]|NIS|PLIP|PortSlave|Remote-bridging|routing|Samba|Sat|SMB|Serial-Lap|Token-Ring|TransparentProxy|Virtual-services|VoIP|UUCP' ],
               net_cfg => [ "Network configuration:", 'Adv-Routing|Authentication-Gateway|Traffic-Control-tcng-HTB' ],
               net_client => [ "Network clients:", 'IRC|Mozilla-Optimization|NC-HOWTO|Thinclient|Web-Browsing-Behind-ISA-Server' ],
               net_server => [ "Network servers:", 'DNS|Fax|Firewall|IP(-Mas|-Sub|CH|v6|X)|Jabber-Server-Farming|phhttpd|PHP|PHP-Nuke|Public-Web-Browser|Sendmail' ],
               office => [ "Office:", 'Bangla|docbook|emacs|Euro-char|Font|StarOffice|tetex|vim|wordperfect' ],
               os => [ "OSes cohabitation:", 'FreeBSD|MultiOS|NT-Loader|OS2|Solaris|Windows|WinNT|Win9' ],
               packaging => [ "Packaging:", 'Debian-Binary-Package-Building|RPM|Software-build' ],
               printing => [ "Printing:", 'print' ],
               programming => [ "Programming:", 'AI-alife|Assembly|Bash-prog|Beautifier|C\+\+Programming|-dlopen|GCC|highquality-apps|Lex-Yacc|IO-port|Java|Multi-distro-dev|NCURSES-Prog|Ncurses-prog|Program-Libra|Programming-Languages|Querying-libiptc|RCS|Serial-prog|Software-Proj-Mgmt|Software-rel|TclTk|valgrind|XML-RPC' ],
               security => [ "Security:", 'chroot-bind|Compressed-TCP|Cryptoloop|Disk-Encryption|mindterm-ssh|mutt-gnupg|Secure-CVS-Pserver|secure-(prog|pop)|Snort-Statistics|SSL-certif|ssl-redhat|security|shadow|User-auth' ],
               servers => [ "Servers:", 'Apache|Caudium|Mail-Queue|Majordomo|MMBase|Postfix|Qmail\+MH|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:", 'Deciding-Linux|Lotus-DominoR5|Outlook-to-Unix-Mailbox|VB6-to-Tcl|Win-to|VMS-to' ],
               x11 => [ "X Window:", '3D-model|FDU|Framebuffer|intkeyb|KDE-GUI-Login-Configuration|LBX|MGR|TT-Debian|X11|XDM|X-app|X-Big|XFree|Xinerama|xterm|Xterm-Title|X-Term|XWindow' ],
               );

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 ||= qq("$file");
            $TITLE =~ s/\.html//;
            #$TITLE =~ s/.*\///;
        }
        $TITLE =~ s/<[^>]*>//g;
        $TITLE =~ s!\n!!;
        $TITLE =~ s/^\s*//; # remove trailling space for correct order
        $TITLE => $file;
    } @HOWTOS_LIST;
    foreach my $class (sort { $classes{$a}->[0] cmp $classes{$b}->[0] } 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";
        }
    }
    print "<LI>Other howtos:\n<UL>";
    output_links_from_list(\%howtos);
    print "</UL>\n";
}

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;
