#!/usr/bin/env perl
use Geo::Coordinates::RDNAP qw/from_rd to_rd dms/;


# 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 ;-)

# Avoid junk node imports, use following line to import valid nodes
# Usage: for file in CNode*/wleiden.conf proxy*/wleiden.conf; do ./genesis-to-py.pl $file; done > py.conf
do($ARGV[0]) || die;

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

$interfaces = join(',',keys %config);
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

print <<EOF;
[$nodename]
location = $location
status = $status
latitude = $lat
longitude = $lon
interfaces = $interfaces
x = $X
y = $Y
masterip = $master_ip
nodetype = $nodetype
name = $nodename
configtype = node

EOF


foreach $if (keys %config) {
    print <<EOF;
[$nodename/$if]
EOF
    %tmp = (
        'configtype' => 'interface',
        'dhcp' => 'no',
        'compass-direction' => '',
        );
    foreach $line  (split('\n',$config{$if})) {
        ($key, $value) = split(/=/,$line);
        if ($key and (lc($key) =~ /^[a-z].*/)) {
            #print "$key : $value\n";
            $value = lc($value);
            if ($key =~ /^type$/i) {
                if ($value eq 'ethernet') {
                    $value = 'eth';
                } else {
                    $value = '11b';
                }
            } elsif ($key =~ /^mode$/i) {
                if ($value eq 'master') {
                    $value = 'ms';
                } else { # managed
                    $value = 'mn';
                }
            } 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/;
                }
                $tmp{'compass-direction'} = $direction;
            } elsif ($key =~ /^gain$/i) {
                $value =~ s/dbi//;
            }
            $tmp{lc($key)} = $value;
        }
    }

    if ( $tmp{type} eq '11b' && $tmp{channel} > 13 ) {
        $tmp{type} = '11a';
    }

    foreach $key (keys %tmp) {
        print "$key=$tmp{$key}\n";
    }
    print "\n";
}
