filesystem: "root"
mode: 0755
path: "/usr/local/bin/non_virtual_ip"
contents:
  inline: |
    #!/usr/libexec/platform-python
    import collections
    import socket
    import struct
    import subprocess
    import sys


    class SubnetNotFoundException(Exception):
        """
        Exception raised when no subnet in the systems ifaces is on the VIP subnet
        """
        pass


    Address = collections.namedtuple('Address', 'index name family cidr scope')

    SUBNET_MASK_LEN = {
        'inet': 32,
        'inet6': 128
    }


    def ntoa(family, num):
        if family == 'inet':
            result = socket.inet_ntoa(struct.pack("!I", num))
        else:
            lo_half = num & 0xFFFFFFFFFFFFFFFF
            hi_half = num >> 64
            result = socket.inet_ntop(socket.AF_INET6,
                                      struct.pack(">QQ", hi_half, lo_half))
        return result


    def aton(family, rep):
        if family == 'inet':
            result = struct.unpack("!I", socket.inet_aton(rep))[0]
        else:
            hi_half, lo_half = struct.unpack(">QQ", socket.inet_pton(socket.AF_INET6, rep))
            result = (hi_half << 64) | lo_half
        return result


    def addr_subnet_int_min_max(addr):
        ip, prefix = addr.cidr.split('/')
        ip_int = aton(addr.family, ip)

        prefix_int = int(prefix)
        mask = int('1' * prefix_int +
                   '0' * (SUBNET_MASK_LEN[addr.family] - prefix_int), 2)

        subnet_ip_int_min = ip_int & mask

        remainder = '1' * (SUBNET_MASK_LEN[addr.family] - prefix_int)
        subnet_ip_int_max = subnet_ip_int_min | (
            0 if remainder == '' else int(remainder, 2))
        return subnet_ip_int_min, subnet_ip_int_max


    def vip_subnet_cidr(vip, addrs):
        try:
            vip_int = aton('inet', vip)
        except Exception:
            vip_int = aton('inet6', vip)
        for addr in addrs:
            subnet_ip_int_min, subnet_ip_int_max = addr_subnet_int_min_max(addr)
            subnet_ip = ntoa(addr.family, subnet_ip_int_min)
            subnet_ip_max = ntoa(addr.family, subnet_ip_int_max)

            sys.stderr.write('Is %s between %s and %s\n' %
                             (vip, subnet_ip, subnet_ip_max))
            if subnet_ip_int_min < vip_int < subnet_ip_int_max:
                subnet_ip = socket.inet_ntoa(struct.pack("!I", subnet_ip_int_min))
                return Address(index="-1",
                               name="subnet",
                               cidr='%s/%s' % (subnet_ip, addr.cidr.split('/')[1]),
                               family=addr.family,
                               scope='')
        raise SubnetNotFoundException()


    def line_to_address(line):
        spl = line.split()
        return Address(index=spl[0][:-1],
                       name=spl[1],
                       family=spl[2],
                       cidr=spl[3],
                       scope=spl[5])


    def interface_cidrs(filter_func=None):
        try:
            out = subprocess.check_output(["ip", "-o", "addr", "show"], encoding=sys.stdout.encoding)
        except TypeError:  # python2
            out = subprocess.check_output(["ip", "-o", "addr", "show"])
        for addr in (line_to_address(line) for line in out.splitlines()):
            if filter_func(addr):
                yield addr


    def non_host_scope(addr):
        return addr.scope != 'host'


    def in_subnet(subnet):
        subnet_ip_int_min, subnet_ip_int_max = addr_subnet_int_min_max(subnet)

        def filt(addr):
            ip, _ = addr.cidr.split('/')
            ip_int = aton(addr.family, ip)
            return subnet_ip_int_min < ip_int < subnet_ip_int_max
        return filt


    def main():
        api_vip, dns_vip, ingress_vip = sys.argv[1:4]
        vips = set(sys.argv[1:4])
        iface_cidrs = list(interface_cidrs(non_host_scope))
        try:
            subnet = vip_subnet_cidr(api_vip, iface_cidrs)

            sys.stderr.write('VIP Subnet %s\n' % subnet.cidr)

            for addr in interface_cidrs(in_subnet(subnet)):
                ip, prefix = addr.cidr.split('/')
                if ip not in vips:
                    print(addr.cidr.split('/')[0])
                    sys.exit(0)
        except SubnetNotFoundException:
            sys.exit(1)

    if __name__ == '__main__':
        main()
