#!/usr/bin/lua

local json = require("luci.jsonc")

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

local f = io.open("/tmp/trm_runtime.json", "r")
if not f then
    io.write(json.stringify({ ok = false, error = "no runtime file" }))
    os.exit(0)
end

local raw = f:read("*a")
f:close()

local rt = json.parse(raw)
if not rt or not rt.data then
    io.write(json.stringify({ ok = false, error = "bad runtime json" }))
    os.exit(0)
end

local d = rt.data
local status = d.travelmate_status or ""
local connected = status:match("^connected") ~= nil
local net_ok = status:match("net ok") ~= nil

local ssid = nil
if d.station_id then
    ssid = d.station_id:match("radio0/(.+)/%-") or d.station_id:match("radio0/(.+)/")
end

io.write(json.stringify({
    ok = true,
    connected = connected,
    net_ok = net_ok,
    ssid = ssid,
    raw_status = status,
}))
