#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from __future__ import division, print_function

"""
    A pure python ping implementation using raw sockets.

    Compatibility:
        OS: Linux, Windows, MacOSX
        Python: 2.6 - 3.5

    Note that due to the usage of RAW sockets root/Administrator
    privileges are requied.

    Derived from ping.c distributed in Linux's netkit. That code is
    copyright (c) 1989 by The Regents of the University of California.
    That code is in turn derived from code written by Mike Muuss of the
    US Army Ballistic Research Laboratory in December, 1983 and
    placed in the public domain. They have my thanks.

    Copyright (c) Matthew Dixon Cowles, <http://www.visi.com/~mdc/>.
    Distributable under the terms of the GNU General Public License
    version 2. Provided with no warranties of any sort.

    website: https://github.com/M-o-a-T/aioping

"""

# TODO Remove any calls to time.sleep
# This would enable extension into larger framework that aren't multi threaded.
import os
import sys
import argparse

from aio_ping import ping

if __name__ == '__main__':
    if sys.argv.count('-T') or sys.argv.count('--test_case'):
        print('Running PYTHON PING test case.')
        # These should work:
        for val in verbose_ping("127.0.0.1"):
            pass
        for val in verbose_ping("8.8.8.8"):
            pass
        for val in verbose_ping("heise.de"):
            pass
        for val in verbose_ping("google.com"):
            pass

        # Inconsistent on Windows w/ ActivePython (Python 3.2 resolves
        # correctly to the local host, but 2.7 tries to resolve to the local
        # *gateway*)
        for val in verbose_ping("localhost"):
            pass

        # Should fail with 'getaddrinfo failed':
        for val in verbose_ping("foobar_url.fooobar"):
            pass

        # Should fail (timeout), but it depends on the local network:
        for val in verbose_ping("192.168.255.254"):
            pass

        # Should fails with 'The requested address is not valid in its context'
        for val in verbose_ping("0.0.0.0"):
            pass

        exit()

    parser = argparse.ArgumentParser(description='A pure python implementation\
                                      of the ping protocol. *REQUIRES ROOT*')
    parser.add_argument('hostname', help='The address to attempt to ping.')

    parser.add_argument('-w', '--deadline', help='The maximum amount of time to\
                         wait until ping times out.', type=float, dest='timeout')

    parser.add_argument('-c', '--request_count', help='The number of attempts \
                        to make. Zero=infinite.', type=int, dest='count')

    parser.add_argument('-i', '--interval', help='Time between ping \
                        attempts', action='store', type=float, dest='interval', \
                        default=1)

    parser.add_argument('-4', '--ipv4', action='store_const', const=False,
                        dest='ipv6', help='Flag to use IPv4.')
    parser.add_argument('-6', '--ipv6', action='store_const', const=True,
                        dest='ipv6', help='Flag to use IPv6.')

    parser.add_argument('-I', '--interface', action='store', help='Interface \
                        to use.', dest='sourceIntf')

    parser.add_argument('-s', '--packet_size', type=int, help='Designate the\
                        amount of data to send per packet.', default=64,
                        dest='numDataBytes')

    parser.add_argument('-T', '--test_case', action='store_true', help='Flag \
                        to run the default test case suite.')

    parser.add_argument('-S', '--source_address', help='Source address from which \
                        ICMP Echo packets will be sent.', dest='sourceIP')

    parsed = parser.parse_args()
    kw=dict((k,v) for k,v in vars(parsed).items() if v is not None)
    kw.pop('test_case',None)

    res = ping(**kw)
    sys.exit(0 if res else 1)

