#!/usr/bin/env lua5.1
--local ut = require 'ngcp.utils'.table
local config = "/etc/kamailio/proxy/dlgcnt.lua.cfg"

local argparse = require "argparse"
local parser = argparse() {
	name = "ngcp-dlgcnt-clean",
	description = "helper to remove kamailio dialogs from redis db"
}

parser:argument("callid", "Call-Id to remove")
parser:flag("-c --config-db", "redis db defined at config")
parser:flag("-C --config-host", "redis server defined at config")

-- luacheck: globals dlg_config
KSR = {}
KSR.log = function (level, str)
	print(string.format("[%s] %s", level, str))
end
function KSR.dbg(message)
	KSR.log("debug", message)
end
function KSR.err(message)
	KSR.log("error", message)
end
function KSR.info(message)
	KSR.log("info", message)
end
function KSR.notice(message)
	KSR.log("info", message)
end
function KSR.warn(message)
	KSR.log("warn", message)
end
function KSR.crit(message)
	KSR.log("fatal", message)
end

local function get_config()
	if os.getenv('DLG_CONFIG') then
	  config = os.getenv('DLG_CONFIG')
	end

	local ok,e = pcall(dofile,config)
	if not ok then
	  io.stderr:write(e..'\n')
	  io.stderr:write("using defaults\n")
	end
end

local args = parser:parse()

get_config()

if args.config_db then
	local val = 4
	if dlg_config then
		val = dlg_config.pair.db
	end
	print(tostring(val))
	os.exit(0)
elseif args.config_host then
	local val = "127.0.0.1"
	if dlg_config then
		val = dlg_config.pair.host
	end
	print(tostring(val))
	os.exit(0)
end

local NGCPDlg = require 'ngcp.dlgcnt'
local dlg = NGCPDlg:new()

if dlg_config then
	dlg.config.central.host = dlg_config.central.host
	dlg.config.central.port = dlg_config.central.port
	dlg.config.central.db = dlg_config.central.db
	dlg.config.pair.host = dlg_config.pair.host
	dlg.config.pair.port = dlg_config.pair.port
	dlg.config.pair.db = dlg_config.pair.db
	--print(string.format("dlg.config:%s", ut.tostring(dlg.config)))
end

dlg:del(args.callid)
