#!/usr/bin/env python3

# Copyright © 2011-2016 Jakub Wilk <jwilk@jwilk.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the “Software”), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

import argparse
import collections
import socket
import sys

description = \
'''
host(1) with Graphviz output.
'''

template_begin = '''
digraph {
    rankdir=LR
    edge [arrowsize=0.5, arrowhead="vee"]
    node [fontsize=10, width=0, height=0, shape=box]
'''

template_end = '''
}
'''

class ArgumentParser(argparse.ArgumentParser):
    def __init__(self):
        argparse.ArgumentParser.__init__(self, description=description)
        self.add_argument('addresses', metavar='ADDRESS', nargs='+', help='IP address or domain name')

class Mapping(object):

    def __init__(self, pending=()):
        self.pending = set(pending)
        self.initial = frozenset(pending)
        self.done = set()
        self.mapping = collections.defaultdict(set)

    def add(self, source, target):
        self.done.add(source)
        if source == target:
            return
        if target not in self.done:
            self.pending.add(target)
        self.mapping[source].add(target)

    def update_all(self):
        while self.pending:
            self.update()

    def update(self):
        address = self.pending.pop()
        try:
            host, _, ips = socket.gethostbyaddr(address)
            for ip in ips:
                self.add(ip, host)
        except (socket.gaierror, socket.herror):
            pass
        try:
            for _, _, _, _, ip in socket.getaddrinfo(address, 0):
                self.add(address, ip[0])
        except socket.gaierror:
            return set()
        self.done.add(address)

    def print(self, stdout=None):
        if stdout is None:
            stdout = sys.stdout
        print(template_begin.strip(), file=stdout)
        for source, targets in self.mapping.items():
            if source in self.initial:
                print('    "{source}" [style=bold]'.format(source=source))
            for target in targets:
                print('    "{source}" -> "{target}"'.format(source=source, target=target), file=stdout)
        print(template_end.strip(), file=stdout)

def main():
    options = ArgumentParser().parse_args()
    mapping = Mapping(pending=options.addresses)
    mapping.update_all()
    mapping.print()

if __name__ == '__main__':
    main()

# vim:ts=4 sts=4 sw=4 et
