#! /usr/bin/env perl

# ICON
#
# ---------------------------------------------------------------
# Copyright (C) 2004-2026, DWD, MPI-M, DKRZ, KIT, ETH, MeteoSwiss
# Contact information: icon-model.org
# See AUTHORS.TXT for a list of authors
# See LICENSES/ for license information
# SPDX-License-Identifier: BSD-3-Clause
# ---------------------------------------------------------------

=encoding utf8

=head1 NAME

mk_index_html - Create a static HTML index page for directory or file list

=head1 SYNOPSIS

B<mk_index_html> [I<option>]... [I<file>]...

=head1 DESCRIPTION

Creates a static HTML index page for use in web applications,
based on a file list if given, else based on the current working directory.

I<mk_index_html> will enable LightBox image browsing for .png or .jpg files
found in file list or directory.
In this case, a subdirectory with support files for LightBox is created.

=head1 OPTIONS

=over

=item B<-a> I<address>

Use I<address> as page footer information.
Default is 'Max-Planck-Institut f&uuml;r Meteorologie'

=item B<-b>

Set up a I<base> index page for top-level directories.
Equivalent to '-f Directory -s -t Index -u'.

=item B<-f> I<file_header>

Use I<file_header> as header of the file name column. Default is 'File'.

=item B<-i> I<file_name>

Use I<file_name> as name for the index file. Default is 'index.html'.

=item B<-p>

Use the full I<path> to the current directory when replacing '%s' in title
(see B<-t>)

=item B<-s>

Suppress file I<size> information.

=item B<-t> I<title>

Use I<title> as title for the index file.
'%s' within I<title> is replaced by the current directory name.
Default is "Index of '%s'",

=item B<-u>

Suppress I<up> link to higher index level.

=item B<-I>

Suppress use of 'index.html' in links.

=back

=head1 SEE ALSO

The LightBox website L<http://lokeshdhakar.com/projects/lightbox2/>

=head1 AUTHOR

Written by Karl-Hermann Wieners

=head1 COPYRIGHT

Copyright (c) X<copyrightdate> Max-Planck-Institut für Meteorologie, Hamburg, Germany

Copying and distribution of this program, with or without modification,
are permitted in any medium without royalty provided the copyright
notice and this notice are preserved.  This program is offered as-is,
without any warranty.

LightBox: Copyright (c) 2007, 2015 Lokesh Dhakar

jQuery: Copyright (c) 2005, 2014 jQuery Foundation, Inc. and other contributors

Sizzle: Copyright (c) 2008, 2014 jQuery Foundation, Inc. and other contributors

=cut

use warnings;
use strict;
use Cwd;
use File::Basename;
use Getopt::Std;

use POSIX qw(strftime);

$Getopt::Std::STANDARD_HELP_VERSION = 1;
$main::VERSION = '$Id: mk_index_html 656 2022-04-19 14:38:56Z m221078 $';

my $program = basename($0);
my $bin_dir = dirname($0);
my $lib_dir = (grep(-d, "$bin_dir/lightbox", "$bin_dir/../share/lightbox"))[0];

my $dir = getcwd;
my $file_name = 'index.html';
my $address = 'Max-Planck-Institut f&uuml;r Meteorologie';

my $hide_size = 0;
my $hide_up = 0;
my $index_name = '/index.html';

my %options;

my @command_line = ($program, @ARGV);

my %directory = ( en => 'Directory', de => 'Verzeichnis' );
my %file = ( en => 'File', de => 'Datei' );
my %index_of = ( en => 'Index of', de => 'Index f&uuml;r' );
my %up = ( en => 'up', de => 'nach oben' );
my %size = ( en => 'Size', de => 'Gr&ouml;&szlig;e' );
my %date = ( en => 'Date', de => 'Datum' );

getopts('i:bf:st:ua:pl:I', \%options) or die "Oops: invalid option\n";

my $lang = 'en';
exists($options{l}) and $lang = $options{l};

my $title = "$index_of{$lang} '%s'";
my $file_header = $file{$lang};

if(exists($options{b})) {
    $file_header = $directory{$lang};
    $hide_size = 1;
    $hide_up = 1;
    $title = 'Index';
}

exists($options{i}) and $file_name = $options{i};
exists($options{f}) and $file_header = $options{f};
exists($options{s}) and $hide_size = 1;
exists($options{t}) and $title = $options{t};
exists($options{u}) and $hide_up = 1;
exists($options{a}) and $address = $options{a};
exists($options{I}) and $index_name = '';

exists($options{p}) or $dir = basename($dir);

$title = sprintf($title, $dir);

open(INDEX_FILE, '>', $file_name) or
    die "Oops: cannot open '$file_name' for writing: $!\n";
select(INDEX_FILE);

my @generator = map {/\s/?"'$_'":$_} (@command_line);
my $generator = "@generator";
my $generator_version = $main::VERSION;

print "
<html>
    <head>
        <meta name='generator' content=\"$generator\">
        <meta name='generator-version' content=\"$generator_version\">
        <meta http-equiv='cache-control' content='no-cache'>
        <meta http-equiv='content-type' content='text/html; charset=utf-8'>
        <title>$title</title>
        <link rel='stylesheet' href='css/lightbox.css'>
    </head>
    <body style='background-color:#FFFFFF'>
        <address>$title".($hide_up ? '' : " | <a href='..$index_name'>$up{$lang}</a>")."</address>
        <hr>
        <div style='height:90%;min-height:90%;overflow:auto'>
        <table>
            <tr>
                <th>$file_header</th>"
. ($hide_size ? '' :
"
                <th>$size{$lang} (bytes)</th>"
) .
"
                <th>$date{$lang} (UTC)</th>
            </tr>
";
my $i = 0;
my $style;
my $need_lightbox = 0;
unless(@ARGV) {
    @ARGV = glob('*');
}
for my $file (@ARGV) {
    -e $file or next;
    $file =~ /index.*\.html/ and next;
    grep {$_ eq $file} qw(css images js) and next;
    my $attributes = '';
    if($file =~ /.*\.(png|jpg)/) {
        $attributes = "data-lightbox='image-set' data-title='$file'";
        $need_lightbox = 1;
    }
    my @stat_info = stat($file);
    if($i % 2) { $style = "style='background-color: #CCCCCC'"; }
    else       { $style = ''; }
    my $size = reverse($stat_info[7]);
    $size =~ s/(\d\d\d)(?!$)/$1,/g;
    $size = reverse($size);
    my $date = strftime('%F %T', gmtime($stat_info[9]));
    print "
            <tr $style>
                <td><a href='$file".(-d $file ? $index_name : '')."' $attributes>$file</a></td>"
. ($hide_size ? '' :
"
                <td align='right'>$size</td>"
) .
"
                <td>$date</td>
            </tr>
";
    ++$i;
}
print "
        </table>
        </div>
        <hr>
        <address>$address</address>
        <script src='js/lightbox-plus-jquery.min.js'></script>
        <script>
            lightbox.option({
              'resizeDuration': 200,
              'wrapAround': true
            })
        </script>
    </body>
<html>
";

select(STDOUT);
close(INDEX_FILE) or die "Sorry: cannot close '$file_name': $!\n";

if($need_lightbox) {
    my $dir_name = dirname($file_name);
    system("
        mkdir -p $dir_name/css $dir_name/images $dir_name/js &&
        cp -u $lib_dir/css/* $dir_name/css &&
        cp -u $lib_dir/images/* $dir_name/images &&
        cp -u $lib_dir/js/* $dir_name/js
    ") == 0 or die "copying of library files failed with code $?\n";
}
