#!/usr/bin/env perl
use File::Basename;
use Module::Load::Conditional qw[check_install];

if (check_install(module => 'Geo::Coordinates::RDNAP')) {
  require Geo::Coordinates::RDNAP;
  Geo::Coordinates::RDNAP->import(qw/from_rd to_rd dms/);
} else {
  sub from_rd {
    return (0,0,0);
  }
}

# RD X,Y -> RD Noorderbreedte, Oosterbreedte
# http://web.inter.nl.net/users/F.Kissels/gps/conversie.html

# Little perl to convert genesis files into python config files,
# Which gonna be used for more logic stuff ;-)

$argc = $#ARGV + 1;
if ($argc == 0) {
  print STDERR  "Usage $ENV{_} <wleiden.conf> ...\n";
  $NODE_DIR = dirname(__FILE__) .  "/../nodes";
  @ARGV=`ls $NODE_DIR/*/wleiden.conf`;
}

if ($argc != 1) {
  # Hack to easy support multiple files without remembering any variable in between
  foreach $file (@ARGV) {
     chomp($file);
     $output = $file;
     $output =~ s/conf$/yaml/;
     print "# Processing $file -> $output\n";
     $CMD=dirname(__FILE__) . "/genesis-to-yaml.pl";
     `$CMD $file > $output`;
  }
  exit 0;
}


do($ARGV[0]) || die;

my %status_labels = ( up => 'up', down => 'dw', planned => 'pl' );

$interfaces = [];
foreach $if (keys %config) {
  push(@interfaces, $if) if ($if =~ m/^[a-z0-9]+$/g);
}
$interfaces = join(",",@interfaces);

if ( ($X =~ /\d+/) and ($Y =~ /\d+/) and ($X > 10) and ($Y > 10)) {
    ($lat, $lon, $h) = from_rd( $X, $Y, 0);
} else {
    $lat = $lon = $h = 0;
}

$status = $status_labels{$status} || 'up'; # ensure reporting a correct status
$comment = $comment || 'None';

print <<EOF;
# Genesis config yaml style
# vim:ts=2:et:sw=2:ai
#
comment   : "$comment"
interfaces: $interfaces
latitude  : $lat
location  : '$location'
longitude : $lon
masterip  : $master_ip
release   : $release
nodename  : $nodename
nodetype  : $nodetype
rdnap_x   : $X
rdnap_y   : $Y
status    : $status
EOF

if ($ileiden =~ /yes/) {
  print "ileiden   : yes\n";
} else {
  print "ileiden   : no\n";
}

foreach $key  ('internalif', 'nat', 'internalroute', 'remote_access', 'gateway', 'firewall_block', 'proxyid') {
  if ($$key) {
    print "$key: $$key\n";
  }
}

foreach $if (keys %config) {
    ($iflabel, $alias) = split(':',$if);
    $iflabel .= "_alias${alias}" if ($alias =~ m/[0-9]/);
    
    print <<EOF;
iface_$iflabel:
EOF
    %tmp = (
        'dhcp' => 'False',
        'compass' => 'None',
        'interface' => $if,
        );
    foreach $line  (split('\n',$config{$if})) {
        ($key, $value) = split(/=/,$line);
        # Remove trailing and leading white spaces
        $value =~ s/^\s+//;
        $value =~ s/\s+$//;
        if ($key and (lc($key) =~ /^[a-z].*/)) {
            #print "$key : $value\n";
            $value = lc($value) if not lc($key) =~ m/(desc|comment)/;
            if ($key =~ /^type$/i) {
                if ($value eq 'ethernet') {
                    $value = 'eth';
                } else {
                    $value = '11b';
                }
            } elsif ($key =~ /^status$/i) {
                if ($value eq 'up') {
                    $value = 'up';
                } else {
                    $value = 'down';
                }
            } elsif ($key =~ /^mode$/i) {
                if ($value eq 'master') {
                    $value = 'ap-wds';
                } else { # managed
                    $value = 'station-wds';
                }
            } elsif ($key =~ /^polar$/i) {
                if ($value eq 'hor') {
                    $value = 'hr';
                } else {
                    $value = 'vr';
                }
            } elsif ($key =~ /^essid$/i) {
                $key = 'ssid';

                # Dirty hack to fetch compass direction of essid
                $value =~ /[a-z]+-([a-z]+)\..*/;
                $direction = $1;
                # Translate into English
                if ($direction ne "omni") {
                    $direction =~ tr/oz/es/;
                }
                # node AMwtrt1 and 'test' directions
                if ($direction eq "wtrtr" or $direction eq "test") {
                    $direction = 'None';
                }
                if ($direction) {
                  $tmp{'compass'} = $direction;
                } else {
                  $tmp{'compass'} = 'None';
                }
            } elsif ($key =~ /^gain$/i) {
                $value =~ s/dbi//;
            }
	    	# Als key niet bestaat, Dan key toevoegen
            $tmp{lc($key)} = $value;
        }
    }
# Status
    if ( ! $tmp{status} ) {
      $tmp{status} = 'up';
    }
    if ( ! $tmp{mode} ) {
      $tmp{mode} = 'station-wds';
    }
    if ( ! $tmp{desc} ) {
      $tmp{desc} = $tmp{comment};
    }
# ethernet2wifi bridges
    if ( $tmp{extra_type} eq 'eth2wifibridge' ) {
        $tmp{type} = 'eth';
    }
# 11a
    if ( $tmp{type} eq '11b' && $tmp{channel} > 13 ) {
        $tmp{type} = '11a';
    }

    foreach $key (sort keys %tmp) {
        printf "  %-11s: '$tmp{$key}'\n", $key;
    }
    print "\n";
}

