#! /usr/bin/perl

# helper script that
#
# (1) writes a list of assigned IP adresses to ARG1, and
#
# (2) writes the FQDN or, if not available, the first IP to ARG2
#
# The address in (2) should be something we can be reached by via network.
#
# usage:
#
# hostip_from_wicked ARG1 ARG2

$up = 0;

# 'wicked show all' is expected to look like this:
=comment
lo              up
      link:     #1, state up
      type:     loopback
      config:   compat:suse:/etc/sysconfig/network/ifcfg-lo
      leases:   ipv4 static granted
      leases:   ipv6 static granted
      addr:     ipv4 127.0.0.1/8 [static]
      addr:     ipv6 ::1/128 [static]

ens7            up
      link:     #2, state up, mtu 1500
      type:     ethernet, hwaddr 52:54:00:05:0a:2c
      config:   compat:suse:/etc/sysconfig/network/ifcfg-ens7

eth1            up
      link:     #3, state up, mtu 1500
      type:     ethernet, hwaddr 52:54:00:d7:57:86
      config:   compat:suse:/etc/sysconfig/network/ifcfg-eth1
      leases:   ipv4 dhcp granted
      leases:   ipv6 dhcp requesting
      addr:     ipv4 10.230.34.112/18 [dhcp]
      route:    ipv4 default via 10.230.63.254
=cut

for (`wicked show all 2>/dev/null`) {
  chomp;
  if(/^(\S+)\s*(\S+)/) {
    $up = $1 ne 'lo' && $2 eq 'up';
    next;
  }
  next unless $up;

  if(/^\s+addr:\s+ipv\S+\s+(\S+)/) {
    $addr = $1;
    $addr =~ s#/.*$##;
    push @addr, $addr;
  }
}

if(@addr) {
  chomp ($host = `hostname -f 2>/dev/null`);
  $host = $addr[0] if $host !~ /\./;

  if($ARGV[0] && open $f, ">$ARGV[0]") {
    print $f "IP addresses:\n";
    print $f "  $_\n" for @addr;
    close $f;
  }

  if($ARGV[1] && open $f, ">$ARGV[1]") {
    print $f "$host\n";
    close $f;
  }
}

