#!/usr/local/bin/python3.6
#
# Copyright (c) 2013-2014, GhostBSD All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistribution's of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
# 2. Redistribution's in binary form must reproduce the above
#    copyright notice,this list of conditions and the following
#    disclaimer in the documentation and/or other materials provided
#    with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES(INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# $Id: netcardmgr.py v 0.1 Saturday, February 08 2014 Eric Turgeon $

from subprocess import Popen, PIPE, call
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()
wifis = 'sysctl -in net.wlan.devices'
wifinics = Popen(wifis, shell=True, stdout=PIPE, close_fds=True,
                 universal_newlines=True)
wifiscards = wifinics.stdout.readlines()
rcconf = open('/etc/rc.conf', 'r').read()

notnics = ["lo", "fwe", "fwip", "tap", "plip", "pfsync", "pflog",
           "tun", "sl", "faith", "ppp", "wlan", "brige", "ixautomation"]

if os.path.exists("/sbin/openrc") is True:
    start_network = 'doas service network start'
    stop_network = 'doas service network stop'
    restart_network = 'doas service network restart'
else:
    start_network = 'doas service netif start'
    stop_network = 'doas service netif stop'
    restart_network = 'doas service netif restart'


class autoConfigure():

    def __init__(self):
        ifncard = netcard[0].rstrip()
        if ifncard != '':
            for line in netcard[0].split():
                card = line.rstrip()
                nc = re.sub(r'\d+', '', line.rstrip())
                if nc not in notnics:
                    if 'ifconfig_%s=' % card in rcconf:
                        print("Your wired network card is already configured.")
                    else:
                        rc = open('/etc/rc.conf', 'a')
                        rc.writelines('ifconfig_%s="DHCP"\n' % card)
                        rc.close()
                        sleep(1)
                        call(stop_network, shell=True)
                        sleep(1)
                        call(start_network, shell=True)
                        sleep(1)
                        if os.path.exists("/sbin/openrc") is True:
                            cmd = "doas service dhcpcd.%s restart" % card
                            call(cmd, shell=True)
                        print("Your wired network card is configured.")

        ifwifi = wifiscards[0].rstrip()
        if ifwifi != '':
            for wlanNum in range(0, 9):
                if 'wlan%s' % wlanNum not in rcconf:
                    break
            for card in wifiscards[0].rstrip().split():
                if 'wlans_%s=' % card in rcconf:
                    print("Your wifi network card is already configured.")
                    if not os.path.exists('/etc/wpa_supplicant.conf'):
                        open('/etc/wpa_supplicant.conf', 'a').close()
                        call('chown root:wheel /etc/wpa_supplicant.conf',
                             shell=True)
                        call('chmod 765 /etc/wpa_supplicant.conf',
                             shell=True)
                    else:
                        call('chown root:wheel /etc/wpa_supplicant.conf',
                             shell=True)
                        call('chmod 765 /etc/wpa_supplicant.conf',
                             shell=True)
                else:
                    rc = open('/etc/rc.conf', 'a')
                    rc.writelines('wlans_%s="wlan%s"\n' % (card, wlanNum))
                    rc.writelines('ifconfig_wlan%s="WPA DHCP"\n' % wlanNum)
                    rc.close()
                    if not os.path.exists('/etc/wpa_supplicant.conf'):
                        open('/etc/wpa_supplicant.conf', 'a').close()
                        call('chown root:wheel /etc/wpa_supplicant.conf',
                             shell=True)
                        call('chmod 765 /etc/wpa_supplicant.conf', shell=True)
                    sleep(1)
                    call(stop_network, shell=True)
                    sleep(1)
                    call(start_network, shell=True)
                    sleep(1)
                    nicslist = 'ifconfig -l'
                    ifconfig = Popen(nicslist, shell=True, stdout=PIPE,
                                     close_fds=True, universal_newlines=True)
                    cardlist = ifconfig.stdout.read()
                    if 'wlan%s' % wlanNum not in cardlist:
                        call(stop_network, shell=True)
                        sleep(1)
                        call(start_network, shell=True)
                        sleep(1)
                    call('ifconfig wlan%s up scan' % wlanNum, shell=True)
                    call('ifconfig wlan%s up scan' % wlanNum, shell=True)
                    sleep(1)
                wlanNum += 1

autoConfigure()
