#coding:utf-8
import os
import subprocess
from locale import str
from _dbus_bindings import Byte
from builtins import set, bytes
import sqlite3
import re
import time

#1.0.1 添加ntp服务器时间
#1.0.2 设置巨型帧
#1.0.3 删除过期文件(日志,失败包)
print("version 1.0.3")

#/proc
f = open("/proc/net/dev", "r")
str_cmd = f.read()
f.close()
listproc_cardname = re.findall("\s+(\S+):", str_cmd)

#interfaces
fr = open("/etc/network/interfaces", "r")
interfaces_content = fr.read(1000)
listface_info = re.findall("(^auto\s(\S+)\n(\S+.*\n){0,4})", interfaces_content, re.M)  #re.M：^$标志将会匹配每一行
listface_cardname = []
mapfaces = {}
for item in listface_info:
    listface_cardname.append(item[1])
    mapfaces[item[1]] = item[0]
    
#samelist,otherlist
samelist = list(set(listface_cardname) & set(listproc_cardname))    #相同的已在interfaces里注册过的
otherlist = list(set(samelist) ^ set(listproc_cardname))     #多出的

print (samelist)
print (listproc_cardname)

#down
for iproc in listproc_cardname:
    if iproc == "lo":
        continue
    cmd = "ifconfig " + iproc + " down"
    os.system(cmd)

#写入到interfaces-------------------------
strfinal = ""
for same in samelist:
    strfinal += mapfaces[same]
    strfinal += "\n"

f = open("./interfaces", "w+")
for other in otherlist:             
    listAlUse = re.findall("^auto\s\S+\n.*\n^address\s\d+.\d+.(\d+).\d+", strfinal, re.M)
    ilistAlUse = []
    for item in listAlUse:
        ilistAlUse.append(int(item))
    sx = 2
    for isx in range(2, 11):
        if isx in ilistAlUse:
            isx += 1
        else:
            sx = isx
            break     
    if "lo" in other:
        strfinal += "auto " + other + "\n"
        strfinal +=  "iface " + other + " inet loopback\n\n"   
        continue 
    elif "wlan" in other:
        continue
    else:
        strfinal += "auto " + other + "\n"
        strfinal += "iface " + other + " inet static\n"
        strfinal += "address 192.168." + str(sx)  + ".5\n"
        strfinal += "netmask 255.255.255.0\n"
        strfinal += "gateway 192.168." + str(sx)  + ".1\n\n"
f.write(strfinal + "\n")                  
f.close()
os.system("mv ./interfaces /etc/network/interfaces") #move

#mac
mapMac = {}
for iproc in listproc_cardname:
    if iproc == "lo":
        continue
    cmd = "cat /sys/class/net/%s/address" % iproc
    ret = subprocess.Popen(cmd, shell=True, stdout = subprocess.PIPE)
    str_b = ret.stdout.read()
    str_cmd = bytes.decode(str_b)
    mapMac[iproc] = str_cmd
listkey = list(mapMac.keys())

for keymapMac in listkey:
    need_while = 1
    need_modify = 0
    while need_while:
        need_while = 0
        item_value = mapMac[keymapMac]
        for ikeymapMac in listkey:
            if keymapMac == ikeymapMac:
                continue
            if item_value != mapMac[ikeymapMac]:
                continue
            same_mac = "%s" % item_value
            lastlist = same_mac.split(":")
            last = lastlist[-1]
            intx = int("%s" % last, 16)
            newintx = hex(intx + 1)
            str_netintx = "%s" % newintx
            str_netintx = str_netintx.split("x")[-1]
 
            if intx + 1 < 10:
                str_netintx = "0" + str_netintx
            elif intx + 1 > 255:
                str_netintx = str_netintx[-2:]    
            lastlist[-1] = str_netintx
            same_mac = ":".join(lastlist)
            mapMac[keymapMac] = same_mac + "\n"
            need_while = 1
            need_modify = 1
            break
        
    if need_modify == 1:    
        cmd = "ifconfig %s hw ether %s" % (keymapMac, same_mac)
        os.system(cmd)
        print(cmd)

#up
listaddrmask = re.findall("^auto\s(\S+)\n.*\naddress\s(\d+.\d+.\d+.\d+)\nnetmask\s(\d+.\d+.\d+.\d+)\n", strfinal, re.M)
for item in listaddrmask:
    cmd = "ifconfig " + item[0] + " up"
    os.system(cmd)
    cmd = "ifconfig %s %s netmask %s" % (item[0], item[1], item[2])
    os.system(cmd)
    cmd = "ifconfig " + item[0] + " mtu 9000 || "    #巨针9000否执行4000
    cmd += "ifconfig " + item[0] + " mtu 4000"
    os.system(cmd)
    
#up wlan
for iproc in listproc_cardname:
    if "wlan" in iproc:
        cmd = "ifconfig " + iproc + " up"
        os.system(cmd)
        print("up wlan")
        
#run ntp server
def ntpserver(sql):
    curs = sql.cursor()
    cursor_addr = curs.execute("SELECT 值 from info_sysconf where 信息名称='serverip_info'")
    addrpath = "null"
    for rowss in cursor_addr:
        addrpath = rowss[0]
    #sql.close()
    #创建/删除 是否校验时间的临时文件
    if not os.path.exists("use_chk_server_time"):
        if addrpath != "null":
            fp = open("use_chk_server_time", "w+")
            fp.write(addrpath)
            fp.close
        
#remove overdue file 5 删除5天前的一些文件
def remove_overfile(sql):
    try:
        curs = sql.cursor()
        int_curtime = int(time.time())
        list_path = []
        #日志文件
        logpath = "null"
        cursor_name = curs.execute("SELECT 值 from info_sysconf where 信息名称='logpath'")
        for row in cursor_name:
            logpath = row[0]
        str_logpath = "%s" % logpath
        if str_logpath == "null":
            raise Exception("filepath is not full")
        list_path.append(str_logpath) 
        #application
        list_path.append("/root/bin-AOI/cnt_net/cnt_log_app/")
        #失败文件
        cursor_name = curs.execute("SELECT 值 from info_sysconf where 信息名称='failpath'")
        for row in cursor_name:
            failpath = row[0]
        str_failpath = "%s" % failpath
        if str_failpath == "null":
            raise Exception("filepath is not full")
        list_path.append(str_failpath) 
        
        #remove
        for item_path in list_path:
            for root, dirs, files in os.walk(item_path):
                for itemfile in files:
                    if root[-1] != "/":
                        root += "/"
                    file = root + itemfile
                    i_time = os.path.getmtime(file)
                    int_time = int(i_time)
                    differ = int_curtime - int_time
                    if differ > 5 * 24 * 60 * 60 :#5 days
                        os.remove(file)
    except Exception as value:
        print(value)

#------------------------------------- 
#网关及wifi设置
try:
    sql = sqlite3.connect("./PARAM.db")
    curs = sql.cursor()
    infouse = 0
    cursor_name = curs.execute("select value from sysparam where name='CntNet_UseName'")
    for row in cursor_name:
        info = row[0]
    cursor_use = curs.execute("select value from sysparam where name='CntNet'")
    for srow in cursor_use:
        infouse = srow[0]
        break
    strinfouse = "%s" % infouse
    for itemstrinfouse in strinfouse:
        infouse = itemstrinfouse
        break
    strname = "%s" % info
    strinfouse = "%s" % infouse
    sql.close()
    
    #创建/删除 是否校验时间的临时文件
    if os.path.exists("use_chk_server_time"):
        os.remove("use_chk_server_time")
        
    if strname == "" or strinfouse == "0":    #有确定使用联网网卡 和 使用联网
        raise Exception("no need use net or no such use card")
    
    if strname not in listproc_cardname:
        raise Exception("card %s not in /proc list" % strname)
    
    if "wlan" not in strname: 
        gateway = "null"
        touch = "^auto\s%s\n(.*\n){3}gateway\s(\d+.\d+.\d+.\d+)\n" % strname
        listUsecard = re.findall(touch, strfinal, re.M)
        if len(listUsecard):
            gateway = listUsecard[0][1]

        if gateway == "null":
            raise Exception("find interfaces netcard route error")
        
        os.system("route add default gw %s" % gateway)
        #base
        fb = open("./base", "w+")
        fb.write("nameserver %s\n" % gateway)
        fb.close()
        os.system("mv ./base /etc/resolvconf/resolv.conf.d/base")
    else:
        os.system("wpa_supplicant -i%s -Dwext -c /etc/wpa_supplicant/wlanpwd.conf &" % strname)
        #os.system("ifconfig %s %s" % (strname, address))
        os.system("dhclient %s &" % strname)
        #os.system("route add default gw %s" % gateway)
        os.system("rm /etc/resolvconf/resolv.conf.d/base")
    
    sql_net = sqlite3.connect("./cnt_net/sysconf.db")
    #获取服务器连接ntp
    ntpserver(sql_net)
    #删除过期文件
    remove_overfile(sql_net)
    sql_net.close()

except sqlite3.OperationalError:
    print("cls：can not find sqlitefile")
except Exception as value:
    print(value)
except NameError:
    print("cls：some param error in db")
finally:
    print("up finish")















