#!/usr/bin/perl
#< gen-servers.pl - 20130424
# Read fgmap.servers file and generate javascript
use strict;
use warnings;

# defaults
my $FGMAP_SERVERS = 'fgmap.servers';
my $TEMPLATE = 'fg_server_map.html';
my $OUTPUT = 'fg_server_map.html';

my $debug_on = 1;
my $def_file = 'C:\OSGeo4W\apache\htdocs\mpmap\fgmap.servers';
my $def_out  = 'C:\OSGeo4W\apache\htdocs\mpmap\temp.js';

if ($debug_on) {
    $FGMAP_SERVERS = $def_file;
    $OUTPUT        = $def_out;
}

####################################
## functions
sub prt($) { print shift; }

sub trim_leading($) {
    my ($ln) = shift;
	$ln = substr($ln,1) while ($ln =~ /^\s/); # remove all LEADING space
    return $ln;
}

sub trim_tailing($) {
    my ($ln) = shift;
	$ln = substr($ln,0, length($ln) - 1) while ($ln =~ /\s$/g); # remove all TRAILING space
    return $ln;
}

sub trim_ends($) {
    my ($ln) = shift;
    $ln = trim_tailing($ln); # remove all TRAINING space
	$ln = trim_leading($ln); # remove all LEADING space
    return $ln;
}

sub trim_all {
	my ($ln) = shift;
	$ln =~ s/\n/ /gm;	# replace CR (\n)
	$ln =~ s/\r/ /gm;	# replace LF (\r)
	$ln =~ s/\t/ /g;	# TAB(s) to a SPACE
    $ln = trim_ends($ln);
	$ln =~ s/\s{2}/ /g while ($ln =~ /\s{2}/);	# all double space to SINGLE
	return $ln;
}

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

###################################

sub load_fgmap_file() {

    open FIL, "<$FGMAP_SERVERS" || die "Unable to open $FGMAP_SERVERS";

    my @lines = <FIL>;

    close FIL;

    my $lncnt = scalar @lines;

    prt("Processing $lncnt lines, from $FGMAP_SERVERS file...\n");

    my ($line,$len,@arr);
    my ($id, $desc, $host, $port, $ip);
    my $js = '';

    foreach $line (@lines) {
        chomp $line;
        $line = trim_all($line);
        $len = length($line);
        next if ($len == 0);
        next if ($line =~ /^\#/);
        next if ($line =~ /^\$/);
        @arr = split(/::/,$line);
        $len = scalar @arr;
        $id = $arr[0];
        if ($len >= 5) {
            $desc = $arr[1];
            $host = $arr[2];
            $port = $arr[3];
            $ip   = $arr[4];
            prt("Adding server [${id}]\n");
            $js .= <<JS;
            fgmap.server_add("${id}",
                "${desc}",
                "${host}", ${port},
                "${ip}");

JS
        } elsif ($len >= 1) {
            prt("Adding server group [${id}]\n");
            $js .= <<JS;
            fgmap.server_group_add("${id}");

JS
        }
    }
    return $js;
}

my $js = load_fgmap_file();

write2file($js,$OUTPUT);
prt("Javascript written to $OUTPUT\n");


# eof
