#!/usr/bin/perl

sub netmask {
  my ($bits) = @_;

  my $binary = 2 ** $bits - 1;

  my $ip1 = $binary & 255;
  my $ip2 = ($binary & (255 << 8)) >> 8;
  my $ip3 = ($binary & (255 << 16)) >> 16;
  my $ip4 = ($binary & (255 << 24)) >> 24;

  return "$ip4.$ip3.$ip2.$ip1";
}

sub neg_netmask {
  my ($bits) = @_;
  my $mask = &netmask ($bits);
  $mask =~ /([0-9]*)\.([0-9]*)\.([0-9]*)\.([0-9]*)/;

  my $ip4 = 255 - $1;
  my $ip3 = 255 - $2;
  my $ip2 = 255 - $3;
  my $ip1 = 255 - $4;

  return "$ip4.$ip3.$ip2.$ip1";
}

sub subnet {
  my ($address, $bits) = @_;

  my $negmask = &neg_netmask ($bits);

  $negmask =~ /([0-9]*)\.([0-9]*)\.([0-9]*)\.([0-9]*)/;
  my $ip4 = $1 + 0;
  my $ip3 = $2 + 0;
  my $ip2 = $3 + 0;
  my $ip1 = $4 + 0;
  $address =~ /([0-9]*)\.([0-9]*)\.([0-9]*)\.([0-9]*)/;
  $ip4 &= $1 + 0;
  $ip3 &= $2 + 0;
  $ip2 &= $3 + 0;
  $ip1 &= $4 + 0;

  return "$ip4.$ip3.$ip2.$ip1";
}

sub broadcast {
  my ($address, $bits) = @_;

  my $mask = &netmask ($bits);

  $mask =~ /([0-9]*)\.([0-9]*)\.([0-9]*)\.([0-9]*)/;
  my $ip4 = $1 + 0;
  my $ip3 = $2 + 0;
  my $ip2 = $3 + 0;
  my $ip1 = $4 + 0;
  $address =~ /([0-9]*)\.([0-9]*)\.([0-9]*)\.([0-9]*)/;
  $ip4 |= $1 + 0;
  $ip3 |= $2 + 0;
  $ip2 |= $3 + 0;
  $ip1 |= $4 + 0;

  return "$ip4.$ip3.$ip2.$ip1";
}

my $i = 0;

$VALUES=`cat /tmp/net.values`;
foreach my $line (split /\n/, $VALUES) {
  if ($line =~ /addr([^=]*)="(.*)"/) {
    $ifc[$i] = $1;
    $addr[$i] = $2;
    $ifnum{$2} = $i;
    $i++;
  }
  elsif ($line =~ /mask([^=]*)="(.*)"/) {
    $mask[$ifnum{$1}] = $2;
  }
}

for (my $j = 0; $j < $i; $j++) {
  $bcast[$j] = &broadcast ($addr[$j], $mask[$j]);
  $oldmask[$j] = &neg_netmask ($mask[$j]);
  $subnet[$j] = &subnet ($addr[$j], $mask[$j]);
}

for (my $j = 0; $j < $i; $j++) {
  print "$ifc[$j]	$addr[$j]	$oldmask[$j]	$bcast[$j]	$subnet[$j]\n";
}
