print("Start Wifi ECN login tool ...")

import urllib.request
import urllib.parse
import sys
import getopt
import os
import json

dir_path = os.path.dirname(os.path.realpath(__file__))

username = ""
password = ""

argv = sys.argv[1:]

try:
    opts, args = getopt.getopt(argv, "hu:p:", ["username=", "password="])
except getopt.GetoptError:
    print('wifiecn.py -u <username> -p <password>')
    sys.exit(2)
for opt, arg in opts:
    if opt == '-h':
        print('wifiecn.py -u <username> -p <password>')
        sys.exit()
    elif opt in ("-u", "--username"):
        username = arg
    elif opt in ("-p", "--password"):
        password = arg

if username == "" or password == "":
    print('wifiecn.py -u <username> -p <password>')
    sys.exit(2)

data = {"action": "authenticate",
        "from_ajax": "true",
        "login": username,
        "password": password,
        "policy_accept": "true",
        "wispr_mode": "false"}

headers = {
    'origin': "https://portailwifi.ec-nantes.fr/",
    'upgrade-insecure-requests': "1",
    'user-agent': "Mozilla/5.0",
    'content-type': "application/x-www-form-urlencoded",
    'accept': "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
    'accept-encoding': "gzip, deflate, br",
    'accept-language': "en-US,en;q=0.8,fr-FR;q=0.6,fr;q=0.4"
}

bin_data = urllib.parse.urlencode(data).encode()

# HTTP Request
targetUrl = "https://portailwifi.ec-nantes.fr/portal_api.php"
status = "NoStatus"

try :
	request = urllib.request.Request(targetUrl, bin_data, headers, method="POST")
	response = urllib.request.urlopen(request).read().decode()
except :
	print("Can't perform an http request against " + targetUrl)
	print("Are you connected to Wifi-ECN ?")
else:

	pydata = json.loads(response)

	try:
		status = pydata['type']
	except:
		try:
			status = pydata['error']['code']
			print("Wifi ECN sent back en error : " + status)
		except:
			print("I can't read WifiECN answer. :-(")

# End of programm
if status == "CONNECT":
	print("Successfully logged as " + username +". :-)")
else:
	print("Something went wrong. Couldn't connect as " + username +".")