#!/usr/bin/python3

import psutil
import time
import sys
import logging
import subprocess
import requests
import socket
import netifaces
from netaddr import IPNetwork, IPAddress

# Threshold in KB
threshold = 100*1000

# Interface
interface = 'wlp4s0'



logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s]  %(message)s",
    handlers=[
        logging.StreamHandler()
    ])
log = logging.getLogger(__name__)

last_traffic = 0

if interface not in netifaces.interfaces():
    log.error(interface + ' was not found')
    sys.exit(1)

while True:
    traffic = psutil.net_io_counters(pernic=True)[interface]

    traffic_wifi = int((traffic.bytes_sent + traffic.bytes_recv)/1024)

    log.info('Traffic on ' + interface + ': ' + str(traffic_wifi) + ' KB')

    if (traffic_wifi - last_traffic) > threshold or traffic_wifi < last_traffic:
        log.warning('Traffic since last mac change above threshold (or traffic counter changed strangely), changing MAC')

        last_traffic = traffic_wifi

        subprocess.run(['ip', 'link', 'set', interface, 'down'])
        subprocess.run(['macchanger', '-r', interface])
        subprocess.run(['ip', 'link', 'set', interface, 'up'])

        timeout = time.time()+20
        ip = "0.0.0.0"

        while True:
            try:
                s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                s.connect(('10.255.255.255', 1))

                ip = s.getsockname()[0]
                
                log.info('Got IPv4 ' + ip)

                s.close()
                
                break
            except:
                time.sleep(1)

            if time.time() >= timeout:
                log.error('Timeout while waiting for IP address')
                break

        if IPAddress(ip) in IPNetwork("172.18.0.0/16"):
            headers = {
                    'Host': 'www.wifionice.de', 
                    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; irv:58.0) Gecko/20100101 Firefox/58.0',
                    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                    'Accept-Language': 'en-US,en;q=0.5',
                    'Referer': 'http://www.wifionice.de/',
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Cookie': 'csrf=42',
                    'Connection': 'keep-alive',
                    'Upgrade-Insecure-Requests': '1'
                }
            try:
                log.info('Trying login to WIFIonICE in 5 seconds ...')

                time.sleep(5)
                
                r = requests.post('http://www.wifionice.de/de/', data={'login': 'true', 'CSRFToken': '42', 'connect': ''}, headers=headers, timeout=15)

                if r.status_code == 200:
                    log.info('Logged in to WIFIonICE')
                else:
                    log.warning('Logging in failed, got status code ' + str(r.status_code))
            except requests.exceptions.ConnectTimeout:
                log.error('Timeout while trying to login, visit http://www.wifionice.de/ to check')
            except:
                log.error('Error while trying to log in')

    time.sleep(10)
