#!/usr/bin/lua

local json = require("luci.jsonc")

local function uci(cmd)
    local h = io.popen("uci " .. cmd .. " 2>&1")
    local out = h:read("*a")
    local ok = h:close()
    return ok, out
end

local function next_uplink_index()
    local h = io.popen("uci show wireless 2>/dev/null | grep -o 'trm_uplink[0-9]*' | grep -o '[0-9]*'")
    local used = {}
    for n in h:lines() do used[tonumber(n)] = true end
    h:close()
    local i = 0
    while used[i] do i = i + 1 end
    return i
end

io.write("Content-Type: application/json\r\n\r\n")

local body = io.read("*a") or ""
local req = json.parse(body)

if not req or not req.ssid or req.ssid == "" then
    io.write(json.stringify({ ok = false, error = "missing ssid" }))
    os.exit(0)
end

local ssid = req.ssid
local key = req.key
local secured = req.secured and true or false

if secured and (not key or key == "") then
    io.write(json.stringify({ ok = false, error = "secured network requires key" }))
    os.exit(0)
end

local idx = next_uplink_index()
local sec = "wireless.trm_uplink" .. idx

local function q(s) return "'" .. tostring(s):gsub("'", "'\\''") .. "'" end

uci("set " .. sec .. "=wifi-iface")
uci("set " .. sec .. ".device='radio0'")
uci("set " .. sec .. ".mode='sta'")
uci("set " .. sec .. ".network='tm_wwan'")
uci("set " .. sec .. ".ssid=" .. q(ssid))
uci("set " .. sec .. ".disabled='0'")
if secured then
    uci("set " .. sec .. ".encryption='psk2+ccmp'")
    uci("set " .. sec .. ".key=" .. q(key))
else
    uci("set " .. sec .. ".encryption='none'")
end

local up = "travelmate.trm_uplink" .. idx
uci("set " .. up .. "=uplink")
uci("set " .. up .. ".device='radio0'")
uci("set " .. up .. ".ssid=" .. q(ssid))
uci("set " .. up .. ".enabled='1'")

local ok_w = uci("commit wireless")
local ok_t = uci("commit travelmate")

io.write(json.stringify({
    ok = (ok_w and ok_t) and true or false,
    ssid = ssid,
    section = "trm_uplink" .. idx,
    secured = secured,
}))
