#!/usr/bin/perl -w
# pcd2html modul pcd2html_create_index
# Copyright Andreas Tille <tille@debian.org>
#
# This modul creates a main index to all subdirectories and
# an index of each subdirectory
## use strict ;
use pcd2html_uti ;
use strict ;

my $debug = 0;

my ( $title, 
     $textfile,
     %item
   ) ;
# Copy CSS file
system "cp -a ${datadir}/" . GetCSS() . ' ' . GetCSS() ;
# Copy needed icons
system "cp -a ${datadir}/*.png ." ;

if ( -f "missing" ) { unlink "missing" ; } ;

$title="PCD created on `date +%Y/%m/%d` using <a href=\"" . GetPcd2HtmlSourceUrl() .
       "\">pcd2html</a>" ;

%item = GetTranslationItems("eng") ;
CreateFooterString ( $item{"lang"}, "index".$item{"text"} ) ;
($title, $textfile) = GetTitle("index", $title, $item{"text"}) ;

my ( $do_create_index_icons, @IndexIcons ) ;
$do_create_index_icons = 1;
if ( CreateHtmlIndex( $title, $textfile ) ) { exit ; }
$do_create_index_icons = 0;

$title="PCD erstellt am " . `date +%d.%m.%Y` . " mittels <a href=\"" . GetPcd2HtmlSourceUrl() .
       "\">pcd2html</a>" ;

%item = GetTranslationItems("deu") ;
CreateFooterString ( $item{"lang"}, "index".$item{"text"} ) ;
($title, $textfile) = GetTitle("index", $title, $item{"text"}) ;

CreateHtmlIndex( $title, $textfile );

sub GetNumImg {
  # count subdirectories mentioned in main rules and number of icons in one line

  my ( $i, $icons ) ;

  $i     = 0 ;
  $icons = 3 ;
  open(RULES, "rules" ) || die "Unable to open rules file\n" ;
  while ( <RULES> ) {
    unless ( /^#/ ) {
      if ( /^\w/ ) { $i++ ; }
    }
    if ( /^#*\s*icons\s*=\s*([0-9]*)/ ) {
      $icons = $1 ;
    }
  }
  close RULES ;

  return ( $i, $icons ) ;
}

sub PrintEntry {
  ## print a single entry in the table of icons
  ## $_[0]  entry to print
  ## $_[1]  number of current entry
  ## $_[2]  number of icons per row
  ## $_[3]  number of entries left
  ##
  ## returns ( $i, $nimg) 

  my ( $entry,    # 
       $i,        # 
       $numicons, # 
       $nimg      # 
     );

  $entry    = $_[0];
  $i        = $_[1];
  $numicons = $_[2];
  $nimg     = $_[3];

#        print "<td width=\"100\" height=\"100\" class=\"icon\" " ;
  print "  <td class=\"icon\">$entry</td>\n" ;
  if ( $i == $numicons ) { 
    print " </tr>\n" ;
    if ( $nimg > 1 ) { print " <tr>\n" ; }
    $i = 0;
  }
  $i++ ;
  $nimg--;

  return ($i, $nimg) ;
}

##############################################################################################
#  create main index and index in subdirectories
#
sub CreateHtmlIndex  {
  my ( $keywords, $title, $textfile, $back, $home, $nums, $size, $html, $jpg, $nimg, $entry, $i,
       $sub, @sortimg, %subtitle, %images, $numicons, $w, $h, $numsubdirs,
       $previndex, $previndextext, $nextindex, $nextindextext, 
       @Indizees, @NextIndizees, @PrevIndizees );

  $title    = $_[0];
  $textfile = $_[1];
  
  File2String( "keywords." . $item{"lang"} ) ;
  File2String( "content." . $item{"lang"} ) ;

  # open main index file for writing
  $html = "index" . $item{"hext"} ;
  unless ( open(HTML, ">$html" ) ) { die "Unable to open $html\n" ; }
  select HTML ;
  MyHtmlStart($title, $keywords, undef, GetCSS(), undef ) ;

  ($back, $home) = GetTextHome($textfile) ;
  MyNavigation($item{"home"}, $item{"top"}, $item{"other"},
               $item{"oicon"}, $item{"otitle"}, $back, $home, '');

  print "<h1>$title</h1>\n<p class=\"justify\">\n" ;
  if ( -f $textfile ) {
    File2HTML( $textfile, 0, $title ) ;
  }
  print "</p>\n<table class=\"index\">\n <tr>\n" ;

  ($nimg, $numicons) = GetNumImg();

  # create table of links to the subdriectories with icon image table
  open(RULES, "rules" ) || die "Unable to open rules file\n" ;

  $i = 1;
  $numsubdirs = 0;
  @IndexIcons = () ;
  @Indizees   = () ;
  while ( <RULES> ) {
    unless ( /^#/ ) {
      if ( /^\w/ ) {
        /([^ ]*) *{(.*)} *\[(.*)\]/ ;
        $sub = $1 ;
        $numsubdirs++;
        if ( $item{"lang"} eq "en" ) {
	    $subtitle{$sub} = $2 ;
        } else {
	    $subtitle{$sub} = $3 ;
        }
        my $tmp_icon = undef ;
        open(SUBRULES, "$sub/rules") || die "Unable to open $sub/rules\n" ;
        while ( <SUBRULES> ) {
          unless ( /^#/ ) {
            s/\s*#.*// ;
            if ( /(\w*):(\w*)\s.*\s\*/ ) {
              $tmp_icon = ExistingPicWithName ( "$sub/${1}_$2" ) ;
              last ;
            }
            unless ( $tmp_icon ) {
              /(\w*):(\w*)\s/ ;
              $tmp_icon = ExistingPicWithName ( "$sub/${1}_$2" ) ;
            }
	  }
        }
        close SUBRULES ;

        @Indizees = ( @Indizees, $sub ) ;
        $entry = "<a href=\"$sub\/" . $item{"index"} . "\">";
        if ( $tmp_icon ) {
          ($w, $h) = ImageSize($tmp_icon);
          $entry = "<a href=\"$sub\/" . $item{"index"} . "\"><img src=\"$tmp_icon\" width=\"$w\" height=\"$h\" ";
          $entry = "$entry alt=\"$sub\" /></a><br />\n   $subtitle{$sub}" ;
        } else {
          $entry = "$entry$subtitle{$sub}</a>" ;
        }
        @IndexIcons   = ( @IndexIcons, $tmp_icon ) ;

        ($i, $nimg) = PrintEntry ( $entry, $i, $numicons, $nimg ) ;
      }
    }
  }
  close RULES ;
  if  ( $do_create_index_icons == 1 ) { CreateIndexIcon(4); }

  if ( $i != 1 ) { print " </tr>\n" ; }
  print "</table>\n" ;

  MyHtmlEnd ( ) ;
  close HTML ;
  select STDOUT ;

  @NextIndizees  = ( ) ;
  @PrevIndizees  = ( "", "" ) ;
  $i             = 0;
  my $subdir ;
  foreach $subdir ( @Indizees ) { 
    @NextIndizees = ( @NextIndizees, $subdir ); 
    if ( $i < $numsubdirs ) { @PrevIndizees = ( @PrevIndizees, $subdir ); }
    $i++ ;
  }
  @NextIndizees = ( @NextIndizees, "" );
  shift( @PrevIndizees ) ;
  shift( @NextIndizees ) ;

  $_ = $back ;
  if ( defined ( $_ ) && /^\.\.\/?/ ) {
      $back = '../' . $back ;
  }
  $_ = $home ;
  if ( defined ( $_ ) && /^\.\.\/?/ ) {
      $home = '../' . $home ;
  }

  foreach $subdir ( @Indizees ) { 
    ### Prevent double '//' in case of first/last index!!!
    $previndextext = shift( @PrevIndizees ) ;
    if ( $previndextext ) { $previndex     = "../" . $previndextext; }
    else                  { $previndex     = ".." ; }
    $nextindextext = shift( @NextIndizees ) ;
    if ( $nextindextext ) { $nextindex     = "../" . $nextindextext; }
    else                  { $nextindex     = ".." ; }
    chdir $subdir ;
    print "Working in $subdir ...\n" ;
    unless ( open(HTML, ">$html" ) ) { die "Unable to open $html\n" ; }
    select HTML ;
    MyHtmlStart( $subtitle{$subdir}, undef, undef, "../".GetCSS(), undef );

    MyNavigation($item{"home"}, $item{"top"}, $item{"other"},
                 $item{"oicon"}, $item{"otitle"}, $back, $home, '../');

    print "<h1>$subtitle{$subdir}</h1>\n" ;

    %images  = () ;
    @sortimg = () ;

    ($nimg, $numicons) = GetNumImg();

    open(RULES, "rules" ) || die "Unable to open rules file\n" ;
    while ( <RULES> ) {
      unless ( /^#/ ) {
        if ( /(\w*):(\w*)\s\s*(\w*)/ ) {
	  $images{"$1_$2"} = $3 ;
          @sortimg         = (@sortimg, "$1_$2") ;
        } 
      }
    }

    @IndexIcons = ( ) ;

    print "<table width=\"100%\">\n <tr>\n  <th class=\"prev\">\n" ;
    # navigation images to the other directories
    print "   <a href=\"$previndex/" . $item{"index"} . '" class="prev">' . 
          "<img src=\"$previndex/index.jpg\" alt=\"$previndextext\" /></a>\n" ;
    print "  </th>\n   <th rowspan=\"2\">\n" ;
    print "   <table class=\"index\">\n <tr>\n" ;
    my $i = 1;
    my $num;
    foreach $num ( @sortimg ) {
      ($title, $textfile) = GetTitle($num, $images{$num}, $item{"text"});

      unless ( defined($title) ) {
	$title = $images{$num} ;
      }

      $jpg = ExistingPicWithName ( $num . $images{$num} ) ;

      if ( defined ($jpg) ) {
        my ( $tmp_icon ) ;
        $size = int ((( stat( $jpg ) )[7]  + 500) / 1000) ;
        $tmp_icon = ExistingPicWithName ( $num ) ;
        ($w, $h) = ImageSize($tmp_icon);
        $entry = '<a href="' . $num . $item{"hext"} . "\"><img src=\"$tmp_icon\" width=\"$w\" height=\"$h\" ";
        $entry = "$entry alt=\"$title\" /></a><br />\n   $title <span class=\"iconsize\">(${size}k)</span>" ;
        @IndexIcons = ( @IndexIcons, $tmp_icon ) ;
      }
      else {
        if ( $item{"lang"} eq "en" ) {
          $_ = $num ;
	  s/_.*// ;
          print STDOUT "To complete insert CD $_ and rerun pcd2html to build $images{$num}.\n" ;
          unless ( open(MISSING, ">>../missing" ) ) { die "Unable to open $html\n" ; }
	  print MISSING "$subdir/$num$images{$num}\n" ;
          close MISSING ;
          $entry = "Image $images{$num} is missing" ;
        } else {
          $entry = "Bild $images{$num} fehlt" ;
        }
      }

      ($i, $nimg) = PrintEntry ( $entry, $i, $numicons, $nimg ) ;
    }
    if  ( $do_create_index_icons == 1 ) { CreateIndexIcon(9); }
    if ( $i != 1 ) { print "    </tr>\n"; }
    print "   </table>\n  </th><th class=\"next\">\n" ;
    print "   <a href=\"$nextindex/" . $item{"index"} . '" class="next">' . 
          "<img src=\"$nextindex/index.jpg\" alt=\"$nextindextext\" /></a>\n" ;
    print "   </th>\n  </tr>\n  <tr>\n" ;
    print "  <th class=\"indexl\">\n" ;
    print IndexLink($item{"index"}, "index", 0);
    print "  </th><th class=\"indexr\">\n" ;
    print IndexLink($item{"index"}, "index", 0);
    print "  </td>\n </tr>\n" ; 
    if ( -f "index" . $item{"text"} ) {
      print "  <tr>\n    <th></th>\n    <th class=\"description\">" ;
      File2HTML( "index" . $item{"text"}, 1, $title ) ;
      print "  </th>\n    <th></th>\n  </tr>\n" ;
    }
    print "</table>\n" ;
    MyHtmlEnd ( '../' ) ;
    close HTML ;
    select STDOUT ;
    chdir ".." ;
  }
  return 0 ;
}

sub CreateIndexIcon {
  my ( $icon, $nicons, $i, @imgs, $minisize, $iconsize, $tile, $cropsize );

  $nicons = $_[0];
  if ( $nicons == 4 ) {
    $minisize = "32x24" ;
    $iconsize = "80x60" ;
    $tile     = "2x2" ;
  } else {
    $minisize = "24x18" ;
    $iconsize = "80x64" ;
    $tile     = "3x3" ;
  }
  $cropsize = GetCropSize($nicons);

  $i    = 0;
  @imgs = () ;

  my $cmdstring ;
  # build mini icons for building directory icon
  foreach $icon ( @IndexIcons ) {
    # Since ImageMagick 6.0.3 convert uses a new syntax
    # system GetConvert() . "-colors 64 -dither -geometry $minisize! $icon $icon.mini 2>> /dev/null" ;
    $cmdstring = GetConvert($icon) . " -colors 64 -dither -geometry $minisize! $icon.mini 2>> /dev/null" ;
    if ($debug) { print STDERR "DEBUG (index/339): $cmdstring\n" ; }
    system "$cmdstring" ;
    @imgs = ( @imgs, "$icon.mini" );
    $i++ ;
    if ( $i == $nicons ) {
      last ;
    }
  }
  # fill with empty icons if necessary
  while ( $i < $nicons ) {
    my $empty = $i . "empty.mini" ;
    # Since ImageMagick 6.0.3 convert uses a new syntax 
    # system "$convert -colors 64 -dither -geometry $minisize! ${datadir}/empty.xpm $empty 2>> /dev/null" ;
    $cmdstring = GetConvert("${datadir}/empty.xpm") . " -colors 64 -dither -geometry $minisize! $empty 2>> /dev/null" ;
    if ($debug) { print STDERR "DEBUG (index/355): $cmdstring ($i)\n" ; }
    system "$cmdstring" ;
    @imgs = ( @imgs, $empty );
    $i++ ;
  }
  my $zwindex = "zwindex.jpg" ;
  $cmdstring = GetMontage() . " -tile $tile -geometry $minisize -size $iconsize @imgs $zwindex" ;
  if ($debug) { print STDERR "DEBUG (index/358): $cmdstring\n" ; }
  system "$cmdstring" ;
  if ( ! -f $zwindex ) {
      if ( -f "$zwindex.0" ) {
	  rename("$zwindex.0", $zwindex) ;
      } else {
	  print STDERR "Problem to create page index\n";
	  return(-1) ;
      }
  }
  # Since ImageMagick 6.0.3 convert uses a new syntax 
  # system "convert -crop $cropsize+1+1 $zwindex index.jpg; rm -f $zwindex* @imgs" ;
  system GetConvert($zwindex) . " -crop $cropsize+1+1 index.jpg; rm -f $zwindex* @imgs" ;
}

