#! /usr/bin/python3 --

import re
import sys
from subprocess import Popen, PIPE

def decode(bytes_):
    return bytes_.decode('utf-8').strip()

def debug(msg, color='red'):
    reset = '\033[m'
    if color == 'red':
        ansi_code = '\033[31m'
    elif color == 'green':
        ansi_code = '\033[32m'
    elif color == 'yellow':
        ansi_code = '\033[33m'
    else:
        print(f"Unknown color: '{color}'", file=sys.stderr, flush=True)
        ansi_code = reset
    print(ansi_code + msg + reset, file=sys.stderr, flush=True)

def run_bash(cmd):
    process = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE, close_fds=True)
    outb, errb = process.communicate()
    errcode = process.returncode
    if errcode != 0:
        debug("There was an error getting the MAC address")
        sys.exit(1)
    out = decode(outb).strip()
    return out

def get_permaddr():
    permaddr = run_bash("ip link show wlan0 | grep permaddr | awk '{ print $6 }'")
    return permaddr

def main():
    mac_address = run_bash("ip link show wlan0 | grep link/ether | awk '{ print $2 }'")
    as_int = int(mac_address.replace(':', ''), 16)
    set_directly = False
    if len(sys.argv) == 2:
        if sys.argv[1] == 'inc':
            debug("Incrementing MAC address by 1", 'green')
            as_int += 1
        elif sys.argv[1] == 'dec':
            debug("Decrementing MAC address by 1", 'green')
            as_int -= 1
        elif sys.argv[1] == 'reset':
            permaddr = get_permaddr()
            if not permaddr:
                debug("MAC address already matches real MAC address, nothing to change", 'yellow')
                return 0
            new_mac = permaddr
            debug(f"Resetting MAC address to {new_mac}", 'green')
            set_directly = True
        else:
            debug(f"Unknown argument: '{sys.argv[1]}'", 'red')
            debug(f"Must be one of: inc, dec, reset", 'red')
            sys.exit(2)
    else:
        debug("No argument provided. Doing default action", 'yellow')
        debug("Incrementing MAC address by 1", 'green')
        as_int += 1
    if not set_directly:
        as_hex = hex(as_int)[2:]
        split_as_hex = []
        for match in list(re.finditer('..', as_hex[::-1])):
            split_as_hex.insert(0, match.group()[::-1])
        new_mac = ':'.join(split_as_hex)
    commands = f'''
        sudo sh -c 'ip link set dev wlan0 down ; ip link set dev wlan0 address {new_mac} ; ip link set dev wlan0 up'
    '''.strip()
    commands = re.sub('\n\s*', '\n', commands)
    print(commands)
    return 0

if __name__ == '__main__':
  sys.exit(main())
