#!/usr/bin/perl -w
# NAME: genconfig.pl
# AIM: Read a directory, and generate config info
# 04/12/2012 - Add -t tile-out, -m map-out, -l layer-out - separate outputs
# 09/11/2012 - Initial cut
use strict;
use warnings;
use File::Basename;  # split path ($name,$dir,$ext) = fileparse($file [, qr/\.[^.]*/] )
use Cwd;
my $os = $^O;
my $PATH_SEP = '/';
if ($os =~ /win/i) {
    $PATH_SEP = "\\";
}

my $pgmname = $0;
if ($pgmname =~ /(\\|\/)/) {
    my @tmpsp = split(/(\\|\/)/,$pgmname);
    $pgmname = $tmpsp[-1];
}

# user variables
my $VERS = "0.0.2 2012-12-04";
#my $VERS = "0.0.1 2012-11-09";
my $in_dir = '';
my $verbosity = 0;
my $out_file = '';
my $tile_file = '';
my $map_file = '';
my $layer_file = '';
my $recursive = 0;
my @in_dirs = ();
my @relief_arr = ();

### program variables
my @warnings = ();
my $cwd = cwd();

# ### DEBUG ###
my $debug_on = 0;
my $def_dir = 'C:\DTEMP';
my $tmp_out = $def_dir.'\tempout.txt';

sub VERB1() { return $verbosity >= 1; }
sub VERB2() { return $verbosity >= 2; }
sub VERB5() { return $verbosity >= 5; }
sub VERB9() { return $verbosity >= 9; }

sub prt($) { print shift; }

sub show_warnings($) {
    my ($val) = @_;
    if (@warnings) {
        prt( "\nGot ".scalar @warnings." WARNINGS...\n" );
        foreach my $itm (@warnings) {
           prt("$itm\n");
        }
        prt("\n");
    } else {
        prt( "\nNo warnings issued.\n\n" ) if (VERB9());
    }
}

sub pgm_exit($$) {
    my ($val,$msg) = @_;
    if (length($msg)) {
        $msg .= "\n" if (!($msg =~ /\n$/));
        prt($msg);
    }
    show_warnings($val);
    exit($val);
}


sub prtw($) {
   my ($tx) = shift;
   $tx =~ s/\n$//;
   prt("$tx\n");
   push(@warnings,$tx);
}

sub append2file {
	my ($txt,$fil) = @_;
	open WOF, ">>$fil" or mydie("ERROR: Unable to open $fil! $!\n");
	print WOF $txt;
	close WOF;
}

sub out_tilecache($) {
    my $name = shift;
    my $txt = <<EOF;

[relief_$name]
 type=WMS
 url=http://maptest.fgx.ch:81/mapnik/mapnikwms2nd.py?&TRANSPARENT=TRUE&
 extension=png
 bbox=-2581134.058442,-5247030.984143,1937287.322561,-728609.603140
 srs=EPSG:3857
 levels=14
 extent_type=loose
 resolutions=17650.08351954296813346446,8825.04175977148406673223,4412.52087988574203336611,2206.26043994287101668306,1103.13021997143550834153,551.56510998571775417076,275.78255499285887708538,137.89127749642943854269,68.94563874821471927135,34.47281937410735963567,17.23640968705367981784,8.61820484352683990892,4.30910242176341995446,2.15455121088170997723

EOF
    prt("$txt\n");
    if (length($tile_file)) {
        append2file($txt,$tile_file);
    } elsif (length($out_file)) {
        append2file($txt,$out_file);
    }
}

sub out_mapnik($$) {
    my ($name,$path) = @_;
    my $txt = <<EOF;

<Layer name="relief_$name" srs="+proj=laea +lat_0=90 +lon_0=-150 +ellps=WGS84 +datum=WGS84 +units=m">
   <StyleName>Relief</StyleName>
    <Datasource>
     <Parameter name="type">gdal</Parameter>
     <Parameter name="band">-1</Parameter>
     <Parameter name="format">tiff</Parameter>
     <Parameter name="file">$path</Parameter>
     </Datasource>
 </Layer>

EOF
    prt("$txt\n");
    if (length($map_file)) {
        append2file($txt,$map_file);
    } elsif (length($out_file)) {
        append2file($txt,$out_file) if (length($out_file));
    }
}


sub fix_dir($) {
    my $rd = shift;
    if (length($rd) && (!(${$rd} =~ /(\\|\/)$/))) {
        ${$rd} .= $PATH_SEP;
    }
}

sub process_dir($);


sub process_dir($) {
    my ($dir) = @_;
    if (! opendir(DIR,$dir)) {
        prtw("WARNING: Unable to open diectory $dir!\n");
        return;
    }
    my @dirs = ();
    my @files = readdir(DIR);
    my $cnt = scalar @files;
    prt("Processing $cnt file items, from directory $dir...\n") if (VERB2());
    my ($file,$n,$d,$e,$path,$ff);
    fix_dir(\$dir);
    foreach $file (@files) {
        next if ($file eq '.');
        next if ($file eq '..');
        $ff = $dir.$file;
        if ( -d $ff) {
            push(@dirs,$ff);
            next;
        }
        next if (!($file =~ /\.tif$/));
        ($n,$d,$e) = fileparse($file , qr/\.[^.]*/ );
        out_tilecache($n);
        $path = $dir.$file;
        out_mapnik($n,$path);
        push(@relief_arr,$n);
    }
    if ($recursive) {
        foreach $dir (@dirs) {
            process_dir($dir);
        }
    }
}

sub process_in_dirs($) {
    my ($ra) = @_;
    my $cnt = scalar @{$ra};
    prt("Processing $cnt directories...\n");
    my ($dir,$i);
    for ($i = 0; $i < $cnt; $i++) {
        $dir = ${$ra}[$i];
        process_dir($dir);
    }
}

sub get_layer_txt1() {
    my $txt = <<EOF;

var relief = new OpenLayers.Layer.WMS( "Relief",
 //"http://maptest.fgx.ch:81/mapnik/tilecache.py?",
  "http://maptest.fgx.ch:81/mapnik/mapnikwms2nd.py?",
 {
 layers: '
EOF
    return $txt;
}

sub get_layer_txt2() {
    my $txt = <<EOF;
 format: 'image/png',
 transparent: true,
 visibility: false
 },
 {
 maxResolution: 17650.08351954296813346446,   /* start zoom level 0 */ 
 minResolution: 137.89127749642943854269     /* stop zoom level 7 */
 }
 );

EOF
    return $txt;
}

sub out_layers($) {
    my ($ra) = @_;
    my $cnt = scalar @{$ra};
    return if (!$cnt);
    my $txt = get_layer_txt1();
    $txt =~ s/\n$//; # remove trailing new line
    my ($name,$rel,$i);
    for ($i = 0; $i < $cnt; $i++) {
        $name = ${$ra}[$i];
        $rel = "relief_$name";
        $txt .= $rel;
        $txt .= "," if (($i + 1) < $cnt);
    }
    $txt .= "'\n";
    $txt .= get_layer_txt2();
    prt("$txt\n");
    if (length($layer_file)) {
        append2file($txt,$layer_file);
    } elsif (length($out_file)) {
        append2file($txt,$out_file);
    }
}


#########################################
### MAIN ###
parse_args(@ARGV);
process_in_dirs(\@in_dirs);
out_layers(\@relief_arr);
prt("Output written to $out_file\n") if (length($out_file));
prt("Tile output appended to $tile_file\n") if (length($tile_file));
prt("Map output appended to $map_file\n") if (length($map_file));
prt("Layer output appended to $layer_file\n") if (length($layer_file));
pgm_exit(0,"");
########################################

sub need_arg {
    my ($arg,@av) = @_;
    pgm_exit(1,"ERROR: [$arg] must have a following argument!\n") if (!@av);
}

sub parse_args {
    my (@av) = @_;
    my ($arg,$sarg);
    while (@av) {
        $arg = $av[0];
        if ($arg =~ /^-/) {
            $sarg = substr($arg,1);
            $sarg = substr($sarg,1) while ($sarg =~ /^-/);
            if (($sarg =~ /^h/i)||($sarg eq '?')) {
                give_help();
                pgm_exit(0,"Help exit(0)");
            } elsif ($sarg =~ /^v/) {
                if ($sarg =~ /^v.*(\d+)$/) {
                    $verbosity = $1;
                } else {
                    while ($sarg =~ /^v/) {
                        $verbosity++;
                        $sarg = substr($sarg,1);
                    }
                }
                prt("Verbosity = $verbosity\n") if (VERB1());
            } elsif ($sarg =~ /^o/) {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                $out_file = $sarg;
                prt("Set out file to [$out_file].\n") if (VERB1());
            } elsif ($sarg =~ /^t/) {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                $tile_file = $sarg;
                prt("Set tile file to [$tile_file].\n") if (VERB1());
            } elsif ($sarg =~ /^m/) {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                $map_file = $sarg;
                prt("Set map file to [$map_file].\n") if (VERB1());
            } elsif ($sarg =~ /^l/) {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                $layer_file = $sarg;
                prt("Set layer file to [$layer_file].\n") if (VERB1());
            } elsif ($sarg =~ /^r/) {
                $recursive = 1;
                prt("Set recursive.\n") if (VERB1());
            } else {
                pgm_exit(1,"ERROR: Invalid argument [$arg]! Try -?\n");
            }
        } else {
            $in_dir = $arg;
            prt("Set input to [$in_dir]\n") if (VERB1());
            push(@in_dirs,$in_dir);
        }
        shift @av;
    }

    if ($debug_on) {
        if (length($in_dir) ==  0) {
            $in_dir = $def_dir;
            prt("Set DEFAULT input to [$in_dir]\n");
            push(@in_dirs,$in_dir);
        }
        if ((length($out_file) == 0) && length($tmp_out)) {
            $out_file = $tmp_out;
        }
        $recursive = 1;
    }
    if (length($in_dir) ==  0) {
        pgm_exit(1,"ERROR: No input files found in command!\n");
    }
}

sub give_help {
    prt("$pgmname: version $VERS\n");
    prt("Usage: $pgmname [options] in-directory\n");
    prt("Options:\n");
    prt(" --help   (-h or -?) = This help, and exit 0.\n");
    prt(" --recursive    (-r) = Recurse into sub-directories.\n");
    prt(" --verb[n]      (-v) = Bump [or set] verbosity. def=$verbosity\n");
    prt(" --out <file>   (-o) = Write output to this file.\n");
    # 04/12/2012 - Add -t tile-out, -m map-out, -l layer-out
    prt(" --tile <file>  (-t) = Append tile-out to this file.\n");
    prt(" --map <file>   (-m) = Append map-out to this file.\n");
    prt(" --layer <file> (-l) = Append layer-out to this file.\n");

}

# eof - genconfig.pl
