#!/usr/bin/python

import sys, argparse
from subprocess import check_output, CalledProcessError

parser = argparse.ArgumentParser(description='Manage wifi')
parser.add_argument('--connect', help='connect to named network')
parser.add_argument('--current', action='store_true', help='show current connection, if any')
parser.add_argument('--disconnect', action='store_true', help='disconnect from wifi')
parser.add_argument('--password', help='use password to connect to named network')
args = parser.parse_args()

nmcli = '/usr/bin/nmcli'

if args.password and args.connect is None:
	parser.error('--password requires a network to --connect to.')

class Wifi:
	def __init__(self, wifiLine):
		(strength, ssid, security, active) = wifiLine.split(':')
		self.strength = int(strength)
		self.ssid = ssid
		self.security = security
		self.active = True if active=='yes' else False

	def __unicode__(self):
		return self.ssid

	def __str__(self):
		return self.__unicode__().encode('utf-8')

	def infoLine(self):
		name = self.ssid
		active = ''
		if self.active:
			active = '*'

		strength = '+'*int(self.strength/20)

		if self.security:
			security = self.security
		else:
			security = 'insecure'

		return "%1s %-20s %-6s%-10s" % (active, name, strength, security)

if not args.connect and not args.disconnect:
	try:
		wifiList = check_output([nmcli, '--terse', '--fields', 'SIGNAL,SSID,SECURITY,ACTIVE', 'device', 'wifi', 'list'])
	except CalledProcessError, error:
		print 'Unable to check wifi:', error.returncode
		print error.output
		sys.exit()

	wifiList = wifiList.strip()
	wifiList = [Wifi(wifi) for wifi in wifiList.splitlines()]
	wifiList.sort(key=lambda x: x.strength, reverse=True)

	if args.current:
		wifi = filter(lambda x: x.active, wifiList)
		if wifi:
			print wifi[0].infoLine()
		else:
			print 'No current connection.'
	else:
		for wifi in wifiList:
			print wifi.infoLine()
		sys.exit()

if args.disconnect:
	disconnection = check_output([nmcli, 'device', 'disconnect', 'wlan0'])
	print disconnection

if args.connect:
	command = [nmcli, 'device', 'wifi', 'connect', args.connect]
	if args.password:
		command.extend(['password', args.password])
	command.extend(['ifname', 'wlan0'])

	try:
		connection = check_output(command)
	except CalledProcessError, error:
		print 'Unable to connect to network:', error.returncode
		print error.output
		sys.exit()
