#! /usr/bin/perl -w
# Copyright (C) 2020-2022 Arne Wichmann <aw@saar.de>
#
# This little thing is distributed under the GNU General Public License,
# version 2. If you need the license, ask your distributor for it.

use strict;

use TOML::Parser;

sub processitem($$);

my $parser = TOML::Parser->new();

my $data = $parser->parse(join("",<>));

# open(L,'leadin') or die "Could not open file 'leadin': $!\n";
# print($leadin);

our($domain)=(".");
our(%eth);

# for now this is quite specific to kaesesalat so this is ok as a default
processitem($data,"kaesesalat"); 

sub processitem($$) { # argument is a reference to a hash
  my($item)=shift;
  my($name)=shift;
  ref($item) eq "HASH" or die "no hash?";

  # this value will be overwritten by each recursion (dynamic scope)
  # so, this is slightly magic, and magic needs explanation
  # local gives a variable a new value which will last _dynamically_ until
  # the end of the current block - that means among others including
  # functions we call - in effect the variable stays the default for all
  # further recursions unless overridden
  local($domain)="$domain";

  if (exists($item->{"isdomain"}) and $item->{"isdomain"}) {
    if (exists($item->{"name"})) {$name=$item->{"name"}}
    $domain="$name.$domain";
    if (exists($item->{"domain"})) {$domain=$item->{"domain"}}

  } else {
    if (exists($item->{"name"})) {$name=$item->{"name"}}
    if (exists($item->{"domain"})) { # should this be supported?
      warn "domain only supported in domain definitions. skipping $name";
      return;
    }
    if (exists($item->{"ethernet"})) {
      if (exists($eth{$item->{"ethernet"}})) {
        push(@{$eth{$item->{"ethernet"}}},"$name.$domain");
      } else {
        $eth{$item->{"ethernet"}}=["$name.$domain"];
      }
    }
  }

  for (sort(keys(%$item))) {
    if (ref($item->{$_}) eq "HASH") { # name
      next if $item->{$_}->{"isdomain"};
      processitem($item->{$_},$_);
    }
  }

  for (sort(keys(%$item))) {
    if (ref($item->{$_}) eq "HASH") { # subdomain
      next unless $item->{$_}->{"isdomain"};
      processitem($item->{$_},$_);
    }
  }

}

for (keys(%eth)) {
  print "host ".$eth{$_}->[0]." {\n  hardware ethernet $_;\n  fixed-address ".
    join(", ",@{$eth{$_}}).";\n}\n";
}
