#!/usr/bin/perl -w

use LWP::Simple;
use Data::Dumper;
use JSON;
use utf8;
use open ':encoding(utf8)';
use open ':std';

unless ($ARGV[0]) {
  print "Usage: $0 https://map03.4830.org/data/nodes.json\n";
  exit 1;
}

$URL=$ARGV[0];

$data = fetch("$URL");

$json = from_json($data, {utf8 => 1});

foreach $node (@{$json->{'nodes'}}) {
#  print "debug1 " . Dumper($node);
#  print "debug2 " . Dumper($node->{'nodeinfo'});
#  print "debug3 " . $node->{'system'}->{'domain_code'} . "\n";
  print join (';',
	      ($node->{'nodeinfo'}->{'hostname'} ? $node->{'nodeinfo'}->{'hostname'} : ''),
	      ($node->{'nodeinfo'}->{'hardware'}->{'model'} ? $node->{'nodeinfo'}->{'hardware'}->{'model'} : ''),
	      ($node->{'nodeinfo'}->{'owner'}->{'contact'} ? $node->{'nodeinfo'}->{'owner'}->{'contact'} : ''),
	      ($node->{'nodeinfo'}->{'system'}->{'domain_code'} ? $node->{'nodeinfo'}->{'system'}->{'domain_code'} : ''),
	      ($node->{'nodeinfo'}->{'system'}->{'gluon_site_code'} ? $node->{'nodeinfo'}->{'system'}->{'gluon_site_code'} : ''),
	      ($node->{'nodeinfo'}->{'system'}->{'site_code'} ? $node->{'nodeinfo'}->{'system'}->{'site_code'} : ''),
	      ($node->{'nodeinfo'}->{'system'}->{'primary_domain_code'} ? $node->{'nodeinfo'}->{'system'}->{'primary_domain_code'} : ''),
	      ($node->{'nodeinfo'}->{'node_id'} ? 'https://map03.4830.org/map/#!v:m;n:' . $node->{'nodeinfo'}->{'node_id'} : '')
 )


   . "\n";
}

#print Dumper($json->{'nodes'});
#print $tree->dump;


sub fetch {
  my $data;
  my $url = shift(@_);
  print "fetching: $url\n";
  $data = get($url);
  return $data;
}
