#!/usr/bin/env python
from threading import Thread
from os import system
from sys import argv
from time import sleep
from socket import inet_aton
from ipcalc import Network

def usage():
	print("Usage: " + argv[0] + " <subnet> [-vi]")
	exit(1)

def ping_ip(host, dictionary):
	response = system("ping -c 1 -w 2 " + host + " > /dev/null 2>&1")
	if response == 0:
		dictionary[host] = True

def main():
	# Check args.
	if len(argv) < 2:
		usage()

	verbose = False
	inverse = False

	for arg in argv[2:]:
		if "v" in arg:
			verbose = True
		if "i" in arg:
			inverse = True

	# Set up dictionary of IPs.
	ip_table = {}
	for i in Network(argv[1]):
		ip_table[str(i)] = False

	# Run the threads
	for key in ip_table:
		t = Thread(target=ping_ip, args=(key,ip_table))
		t.start()

	# Wait for threads to finish up.
	sleep(3)

	# Sort by IP using socket function inet_aton.
	sorted_table = sorted(ip_table.items(), key=lambda item: inet_aton(item[0]))
	
	for k in sorted_table:
		if verbose:
			if k[1]:
				print(k[0] + " UP")
			else:
				print(k[0] + " DOWN")
		elif inverse:
			if not k[1]:
				print(k[0])
		else:
			if k[1]:
				print(k[0])

if __name__ == "__main__":
	main()
