[%
# vi: ft=tt2

# Return an array of shared IPs for a given host.
#
# @param argv.site      The site to use, default value: current.
# @param argv.host      The host to get all shared IPs for.
# @param argv.type      The interface type or empty string for all types.
# @param argv.status    node status [ online, offline, inactive ]
#                         default value: ['online', 'inactive']
# @param argv.format    Return a flat list (default) or a list of hashes ('hash')
# @return out           The array of shared IPs.

IF !argv.site.length;
  argv.site = 'current';
END;

IF !sites.${argv.site}.hosts.${argv.host}.defined;
  argv.host = 'self';
END;

IF !argv.type.length;
  argv.type = '.*';
END;

IF !argv.status.size;
  argv.status = ['online', 'inactive'];
END;

status = {
  online = 0
  offline = 0
  inactive = 0
};
FOREACH val IN argv.status;
  status.$val = 1;
END;

out = [];
IF status.item(sites.${argv.site}.hosts.${argv.host}.status);
  FOREACH iface IN sites.${argv.site}.hosts.${argv.host}.interfaces;
    NEXT UNLESS sites.${argv.site}.hosts.${argv.host}.exists(iface);
    NEXT UNLESS sites.${argv.site}.hosts.${argv.host}.$iface.type.grep('^' _ argv.type _ '$').size();

    FOREACH ip IN sites.${argv.site}.hosts.${argv.host}.$iface.shared_ip;
      NEXT UNLESS ip;
      IF argv.format == 'hash';
        PERL; -%]
          use Net::Netmask;
          my $network = Net::Netmask->new("[% ip %]/[% sites.${argv.site}.hosts.${argv.host}.$iface.netmask %]");
          $stash->set(netmask_bits => $network->bits);
[%      END;
        out.push({
          ip = ip,
          interface = iface,
          netmask = sites.${argv.site}.hosts.${argv.host}.$iface.netmask,
          bits = netmask_bits
        });
      ELSE;
        out.push(ip);
      END;
    END;
  END;
END;
IF argv.format == 'hash';
  out = out.sort('ip');
ELSE;
  out = out.sort;
END;

-%]
