#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os, re, sys
from db import conn_scope
from config import config

errstr  = '> /dev/null 2>&1'
cmddir  = '/usr/local/bluedon/bdwafd/gencert.py'
getinf  = 'ifconfig -a'
rexpinf = re.compile(r'HWaddr (\S+)')
macfile = '/etc/udev/rules.d/70-persistent-net.rules'
bakfile = '/etc/udev/rules.d/70-persistent-net.rules.bak'

notes1  = '# This file was automatically generated by the /lib/udev/write_net_rules\n' + \
          '# program, run by the persistent-net-generator.rules rules file.\n\n' + \
          '# You can modify it, as long as you keep each rule on a single\n' + \
          '# line, and change only the value of the NAME= key\n\n'

notes2  = ['# PCI device 0x8086:/sys/devices/pci0000:00/0000:00:1c.0/0000:01:00.0 (e1000e)\n',
           '# PCI device 0x8086:/sys/devices/pci0000:00/0000:00:01.0/0000:01:00.0 (igb)\n']

ifinfo  = ['SUBSYSTEM==\"net\", ACTION==\"add\", DRIVERS==\"?*\", ATTR{address}==',
           ', ATTR{dev_id}==\"0x0\", ATTR{type}==\"1\", KERNEL==\"eth*\", NAME=']

def makelicens():
    #init license database
    cmdstr    = cmddir + ' option=4 ' + errstr
    os.system(cmdstr)
    p = os.popen(cmddir)
    lines = p.readlines()
    for line in lines:
        pass

    #make license
    mklicense = cmddir + ' option=1 ' + 'serial=' + line[:-1] + ' expire=\"2030-01-01 00:00:00\"'
    os.system(mklicense)

    #Verification license
    vflicense = cmddir + ' option=2'
    os.system(vflicense)


def modifyinf(num):
    macinfo = []
    num = int(num)
    p = os.popen(getinf)
    lines = p.readlines()
    for line in lines:
        if(line[0:3] == 'eth'):
           match = rexpinf.search(line)
           if(match):
               macinfo.append(match.group(1))
    macinfo = sorted(macinfo)
    infnum = len(macinfo)

    cpfile = 'cp ' + macfile + ' ' + bakfile
    os.system(cpfile)
    fp = open(macfile, 'w')
    fp.write(notes1)
    for i in range(num):
        fp.write(notes2[0])
        macstr = '\"' + macinfo[i] + '\"'
        fp.write(ifinfo[0])
        fp.write(macstr)
        infname = '\"eth' + str(i) + '\"\n\n'
        fp.write(ifinfo[1])
        fp.write(infname)

    if(num <= infnum):
        for i in range(num, infnum):
            fp.write(notes2[1])
            macstr = '\"' + macinfo[i] + '\"'
            fp.write(ifinfo[0])
            fp.write(macstr)
            infname = '\"eth' + str(i) + '\"\n\n'
            fp.write(ifinfo[1])
            fp.write(infname)
    fp.close()


if __name__ == '__main__':
    if(sys.argv[1] == 'dd'):
        if(sys.argv[2][0:3] != 'if=' or sys.argv[3][0:3] != 'of='):
            print "error: dd if=xx of=xx 6"
            exit(0)
        modifyinf(sys.argv[4])

        ddstr = 'dd ' + sys.argv[2] + ' ' + sys.argv[3] 
        ddstr += ' bs=4096k&watch -n 5 pkill -USR1 ^dd$'
        os.system(ddstr)
    elif(sys.argv[1] == 'mysql'):
        if(len(sys.argv) < 4):
            print "error: mysql DB-WAF-G40000 031088890"
            exit(0)
        makelicens()

        with conn_scope(**config['db']) as (conn, cursor):
            sqltc = 'truncate table t_nicsflow;'
            cursor.execute(sqltc)
            sqlup = 'update t_devinfo set model=\'' +  sys.argv[2] + '\','
            sqlup += 'serial_num=\'' + sys.argv[3] + '\';'
            cursor.execute(sqlup)