#!/usr/local/bin/python3.9

from subprocess import Popen, PIPE
import os
import re
from time import sleep

ncard = 'ifconfig -l'
nics = Popen(ncard, shell=True, stdout=PIPE, close_fds=True,
             universal_newlines=True)
netcard = nics.stdout.readlines()[0].rstrip()
wifis = 'sysctl -in net.wlan.devices'
wifinics = Popen(wifis, shell=True, stdout=PIPE, close_fds=True,
                 universal_newlines=True)
wifiscard = wifinics.stdout.readlines()[0].rstrip()
rcconf = open('/etc/rc.conf', 'r').read()
if os.path.exists('/etc/rc.conf.local'):
    rcconflocal = open('/etc/rc.conf.local', 'r').read()
else:
    rcconflocal = "None"

notnics = [
    "enc",
    "lo",
    "fwe",
    "fwip",
    "tap",
    "plip",
    "pfsync",
    "pflog",
    "ipfw",
    "tun",
    "sl",
    "faith",
    "ppp",
    "bridge",
    "ixautomation",
    "vm-ixautomation",
    "wg"
]

cmd = "kenv | grep rc_system"
rc_system = Popen(cmd, shell=True, stdout=PIPE, universal_newlines=True)
if 'openrc' in rc_system.stdout.read():
    openrc = True
    rc = 'rc-'
    network = 'network'
else:
    openrc = False
    rc = ''
    network = 'netif'

restart_network = f'{rc}service {network} restart'


class autoConfigure():

    def __init__(self):
        for line in netcard.split():
            card = line.rstrip()
        # VLAN tags in ifconfig are delimited by period
        # but in rc.conf delimiter is underscore
            card = card.replace(".", "_")
            nc = re.sub(r'\d+', '', line.rstrip())
            if nc not in notnics:
                if f'ifconfig_{card}=' in (rcconf or rcconflocal):
                    print("Your wired network card is already configured.")
                else:
                    rc = open('/etc/rc.conf', 'a')
                    rc.writelines(f'ifconfig_{card}="DHCP"\n')
                    rc.close()
                    sleep(1)
                    os.system(restart_network)
                    sleep(1)
                    if os.path.exists("/sbin/openrc") is True:
                        cmd = f"rc-service dhcpcd.{card} restart"
                        os.system(cmd)
                    print("Your wired network card is configured.")

        for card in wifiscard.split():
            for wlanNum in range(0, 9):
                if f'wlan{wlanNum}' not in (rcconf + rcconflocal):
                    break
            if f'wlans_{card}=' in (rcconf + rcconflocal):
                print("Your wifi network card is already configured.")
                if not os.path.exists('/etc/wpa_supplicant.conf'):
                    open('/etc/wpa_supplicant.conf', 'a').close()
                    os.system('chown root:wheel /etc/wpa_supplicant.conf')
                    os.system('chmod 765 /etc/wpa_supplicant.conf')
                else:
                    os.system('chown root:wheel /etc/wpa_supplicant.conf')
                    os.system('chmod 765 /etc/wpa_supplicant.conf')
            else:
                rc = open('/etc/rc.conf', 'a')
                rc.writelines(f'wlans_{card}="wlan{wlanNum}"\n')
                rc.writelines(f'ifconfig_wlan{wlanNum}="WPA DHCP"\n')
                rc.close()
                if not os.path.exists('/etc/wpa_supplicant.conf'):
                    open('/etc/wpa_supplicant.conf', 'a').close()
                    os.system('chown root:wheel /etc/wpa_supplicant.conf')
                    os.system('chmod 765 /etc/wpa_supplicant.conf')
                sleep(1)
                os.system(restart_network)
                sleep(1)
                nicslist = 'ifconfig -l'
                ifconfig = Popen(nicslist, shell=True, stdout=PIPE,
                                 close_fds=True, universal_newlines=True)
                cardlist = ifconfig.stdout.read()
                if f'wlan{wlanNum}' not in cardlist:
                    sleep(1)
                    os.system(restart_network)
                    sleep(1)
                os.system(f'ifconfig wlan{wlanNum} up scan')
                os.system(f'ifconfig wlan{wlanNum} up scan')
                sleep(1)
            wlanNum += 1


autoConfigure()
