#!/usr/bin/lua
local nixio = require("nixio")
local mtkwifi = require("mtkwifi")

if pcall(require, "map_helper") then
    map_help = require "map_helper"
end

function get_bss_config_priority()
    local r = {}
    local p1905_cfgs = mtkwifi.load_profile("/etc/map/1905d.cfg")
    if not p1905_cfgs then
        r['status'] = "Failed to load /etc/map/1905d.cfg file!"
    else
        r['status'] = 'SUCCESS'
        r['bss_config_priority'] = p1905_cfgs['bss_config_priority']
    end
    return r
end

function get_easymesh_bss_index(bss_config_priority, bssIfname)
    assert(type(bss_config_priority) == 'string')
    assert(type(bssIfname) == 'string')
	local tmp = ""
	local bssInfoIdx = 0
	tmp = string.split(bss_config_priority, ";")
    for bssIdx = 1, #tmp do
        if  string.sub(tmp[bssIdx], 1, string.len(bssIfname)-1 ) == string.sub(bssIfname, 1, string.len(bssIfname)-1 ) then
            bssInfoIdx = bssInfoIdx + 1
        end
        if  tmp[bssIdx] == bssIfname then
            return bssInfoIdx
        end
    end
    return nil
end

function update_easymesh_bss(cfgs, bssInfoInp, bssIfname)
    assert(type(cfgs) == 'table')
    assert(type(bssInfoInp) == 'table')
    if not cfgs[bssInfoInp['alMac']] then
        cfgs[bssInfoInp['alMac']] = {}
    end
    if not cfgs[bssInfoInp['alMac']][bssInfoInp['band']] then
        cfgs[bssInfoInp['alMac']][bssInfoInp['band']] = {}
    end
    local bssInfoTbl = cfgs[bssInfoInp['alMac']][bssInfoInp['band']]
    local bssInfoIdx
	local r = get_bss_config_priority()
	assert(r['status'] == 'SUCCESS');
   
    bssInfoIdx = get_easymesh_bss_index(r['bss_config_priority'], bssIfname)
	if not bssInfoIdx then return end
	
    assert(type(bssInfoTbl[bssInfoIdx]) == 'table')
  
    local bssInfo = bssInfoTbl[bssInfoIdx]
    bssInfo['ssid'] = bssInfoInp['ssid']
    bssInfo['authMode'] = bssInfoInp['authMode']
    bssInfo['encType'] = bssInfoInp['encType']
    bssInfo['passPhrase'] = bssInfoInp['passPhrase'] and bssInfoInp['passPhrase'] ~= '' and bssInfoInp['passPhrase'] or '12345678'
    bssInfo['isBhBssSupported'] = bssInfoInp['isBhBssSupported']
    bssInfo['isFhBssSupported'] = bssInfoInp['isFhBssSupported']
    bssInfo['isHidden'] = bssInfoInp['isHidden']
end

function easymesh_bss_cfg(bssCfg, bssIfname)
    local cfgs = mtkwifi.load_easymesh_bss_cfgs()
    local bssInfoInp = {}
	assert(type(bssCfg) == 'string')
    assert(type(bssIfname) == 'string')
	
	local tmp = ""
	tmp = string.split(bssCfg, " ")
	
	bssInfoInp['alMac'] = string.upper(tmp[1])
	bssInfoInp['band'] = tmp[2]
	bssInfoInp['ssid'] = tmp[3]
	bssInfoInp['authMode'] = tmp[4]
	bssInfoInp['encType'] = tmp[5]
	bssInfoInp['passPhrase'] = tmp[6]
	bssInfoInp['isBhBssSupported'] = tmp[7]
	bssInfoInp['isFhBssSupported'] = tmp[8]
	bssInfoInp['isHidden'] = tmp[9]

    if type(cfgs) ~= "table" or next(cfgs) == nil then
		cfgs = {}
        cfgs['wildCardAlMacCfgs'] = {}
        cfgs['distinctAlMacCfgs'] = {}
    end
    if bssInfoInp['alMac'] == 'FF:FF:FF:FF:FF:FF' then
        update_easymesh_bss(cfgs['wildCardAlMacCfgs'], bssInfoInp, bssIfname)
    else
        update_easymesh_bss(cfgs['distinctAlMacCfgs'], bssInfoInp, bssIfname)
    end
    mtkwifi.save_easymesh_bss_cfgs(cfgs)
	
end

function update_all_easymesh_bss_cfgs()
    local cfgs = mtkwifi.load_easymesh_bss_cfgs()
    local shuci = require("shuci")
    local uci = shuci.decode("/tmp/usr/config/wireless")
	local wifiiface = uci['wifi-iface']
    local cfgs = mtkwifi.load_easymesh_bss_cfgs()
	local bssInfoTbl = cfgs['wildCardAlMacCfgs']['FF:FF:FF:FF:FF:FF']
	local bssInfoIdx
	local bandIdx
	local r = get_bss_config_priority()
	assert(r['status'] == 'SUCCESS');

	for bssIdx, bssInfo in pairs(wifiiface) do      
		if bssInfo['mode'] == 'ap' then
			bssInfoIdx = get_easymesh_bss_index(r['bss_config_priority'], bssInfo['ifname'])
			print("bssInfo ifname "..bssInfo['ifname'])
			
			if	bssInfo['device'] == '2G'  then
				bandIdx = '8x'
			else
				bandIdx = '11x'
			end	
			
			if	bssInfoIdx and
				type(bssInfoTbl[bandIdx][bssInfoIdx]) == 'table' then
				bssInfo['ssid'] = string.gsub(bssInfo['ssid'], "\\", "\\\\")
				bssInfo['ssid'] = string.gsub(bssInfo['ssid'], " ", "\\ ")
				bssInfoTbl[bandIdx][bssInfoIdx]['ssid'] = bssInfo['ssid']
				-- bssInfoTbl[bandIdx][bssInfoIdx]['authMode']
				-- bssInfoTbl[bandIdx][bssInfoIdx]['encType']
				if bssInfo['encryption'] == 'none' then
					bssInfoTbl[bandIdx][bssInfoIdx]['authMode'] = '0x0001'
					bssInfoTbl[bandIdx][bssInfoIdx]['encType'] = '0x0001'
				elseif bssInfo['encryption'] == 'psk2+ccmp' then
					if bssInfo['sae'] == '1' then
						bssInfoTbl[bandIdx][bssInfoIdx]['authMode'] = '0x0060'
						bssInfoTbl[bandIdx][bssInfoIdx]['encType'] = '0x0008'
					else
						bssInfoTbl[bandIdx][bssInfoIdx]['authMode'] = '0x0020'
						bssInfoTbl[bandIdx][bssInfoIdx]['encType'] = '0x0008'
					end
				else
					bssInfoTbl[bandIdx][bssInfoIdx]['authMode'] = '0x0022'
					bssInfoTbl[bandIdx][bssInfoIdx]['encType'] = '0x0008'
				end
				if bssInfo['key'] then
					-- QIHOO_EDIT, need decrypt key
					bssInfo['key'] = mtkwifi.read_pipe("safepwd -d "..bssInfo['key'])
					bssInfo['key'] = string.sub(bssInfo['key'], 1, string.len(bssInfo['key']) - 1)
					-- QIHOO_EDIT end
					bssInfo['key'] = string.gsub(bssInfo['key'], "\\", "\\\\")
					bssInfo['key'] = string.gsub(bssInfo['key'], " ", "\\ ")
					bssInfoTbl[bandIdx][bssInfoIdx]['passPhrase'] = bssInfo['key']
				else
					bssInfoTbl[bandIdx][bssInfoIdx]['passPhrase'] = '12345678'
				end
				-- bssInfoTbl[bandIdx][bssInfoIdx]['isBhBssSupported']
				-- bssInfoTbl[bandIdx][bssInfoIdx]['isFhBssSupported']
				if bssInfo['hidden'] == '1' then
					bssInfoTbl[bandIdx][bssInfoIdx]['isHidden'] = 'hidden-Y'
				else
					bssInfoTbl[bandIdx][bssInfoIdx]['isHidden'] = 'hidden-N'
				end
				print("bssInfo "..bandIdx.."bssInfoIdx"..bssInfoIdx.." ssid "..bssInfo['ssid'])
			end	
		end	
	end 
	mtkwifi.save_easymesh_bss_cfgs(cfgs)
end

function apply_easymesh_bss_cfg()
	local devRole = c_get_device_role()
	if tonumber(devRole.mapDevRole) == 1 then
		local r = c_apply_bss_config_renew()
		if r['status'] == 'SUCCESS' then
			print('apply_easymesh_bss_cfg c_apply_bss_config_renew SUCCESS!')
		else
			print('apply_easymesh_bss_cfg c_apply_bss_config_renew fail!')
			print(r['status'])
		end
	end
end

bssIfname = arg[1]
bssCfg = arg[2]
print("input args: ifname ="..bssIfname)

if bssIfname == 'all' then
	update_all_easymesh_bss_cfgs()
else
	print("input args: bssCfg ="..bssCfg)
	easymesh_bss_cfg(bssCfg, bssIfname)
end

if arg[2] == 'renew' or
	arg[3] == 'renew' then
	apply_easymesh_bss_cfg()
	print('call bssCfg renew...')
end

