#!/opt/lnxall/bin/lua

-- Created by jiaqiang.ye@lnxall.com
-- Simple troubleshooting for CentOS-7 & openwrt
-- 20230508

-- load external Lua modules
local posix = require 'posix'
local invoker = require 'invoker'

-- global variables
local g_ttydev = nil   -- path of controlling ttyUSB for 4G modem
local G_SEPLINE = "****************************************************************\n"

local function ts_init()
	if posix.access('/opt/lnxall/bin/lua') == 0 then
		posix.setenv('PATH', '/opt/lnxall/bin:/usr/bin:/usr/sbin:/bin:/sbin', true)
	end
	local ttydev = invoker.readfile('/tmp/4g_modem_tty', invoker.TRIMEND)
	if type(ttydev) ~= "string" then
		io.stderr:write("Error, failed to read 4g_modem_tty!\n")
		io.stderr:flush()
		return false
	end
	g_ttydev = ttydev
	return true
end

local function run_comgt(imsg, script)
	local okay = true
	local paths = '/etc/gcom/' .. script
	if posix.access(paths) ~= 0 then
		okay = false
		paths = '/opt/lnxall/etc/gcom/' .. script
		if posix.access(paths) == 0 then okay = true end
	end

	if not okay then
		io.stderr:write(string.format("Error, script not found: '%s'\n", script))
		io.stderr:flush()
		return false
	end

	io.stdout:write(G_SEPLINE)
	if type(imsg) == "string" then io.stdout:write(imsg) end
	io.stdout:flush()
	invoker.invoke(invoker.CLOSEFD, 'comgt', '-d', g_ttydev, '-s', paths)
	io.stdout:flush(); io.stderr:flush()
	return true
end

local function ts_main()
	if ts_init() then
		io.stdout:write("Modem info:\n"); io.stdout:flush()
		invoker.invoke(invoker.CLOSEFD, 'comgt', '-d', g_ttydev, 'info')
		run_comgt("sim status:\n",      'checksim.gcom')
		run_comgt("vendor info:\n",     'getvendor.gcom')
		run_comgt("imei info:\n",       'getimei.gcom')
		run_comgt("imsi info:\n",       'getimsi.gcom')
		run_comgt("iccid info:\n",      'geticcid.gcom')
		run_comgt("cardinfo:\n",        'getcardinfo.gcom')
		run_comgt("signal strength:\n", 'getstrength.gcom')
		run_comgt("carrier info:\n",    'getcarrier.gcom')
		run_comgt("PING result:\n",     'ping.gcom')
		run_comgt("APN config:\n",      'getcgdcont.gcom')
		run_comgt("Connect status:\n",  'getcgcontrdp.gcom')
	end

	io.stdout:write(G_SEPLINE)
	io.stdout:write("route info:\n")
	invoker.invoke(invoker.CLOSEFD, 'ip', 'route', 'show')

	io.stdout:write(G_SEPLINE)
	io.stdout:write("interface info:\n")
	invoker.invoke(invoker.CLOSEFD, 'ip', 'addr', 'show')

	io.stdout:write(G_SEPLINE)
	io.stdout:write("dns info:\n")
	invoker.invoke(invoker.CLOSEFD, 'nslookup', 'mqtt.lnxall.com')

	return true
end

ts_main()
os.exit(0)
