def _get_pos_status(pos):
	e = xt_func.sh(["ip link show up | grep", pos])
	if e[0] is False:
		return "Down"

	raw = xt_func.sh(["ethtool", pos, "| egrep 'Speed|Duplex'"])[1].split()
	m = re.match("(\d+)", raw[1])
	if m is None:
		return "Unknown"
	return m.group(1) + "/" + raw[3]
def _set(data):
	ret = True
	emsg = []
	tzcode = tz.TZ[data["time-zone"]]
	e = xt_func.sh(["echo '"+ tzcode+ "'", "| sudo tee /etc/TZ"])
	if not e[0]:
		ret = False
		emsg.append(e[1])

	f = open(const.CRON_SH["ntpd"], "w")
	f.write("#!/bin/sh\n")
	if data["time-server"] != "":
		f.write("sleep 30\n")
		f.write("ntpd -qnNp "+ data["time-server"]+ "\n")
		f.write("hwclock -w\n")
	f.close()

	e = xt_func.sudo([const.CRON_SH["ntpd"]], block=False)
	if not e[0]:
		ret = False
		emsg.append(e[1])

	d = datetime.datetime.today()
	run_at = str(d.second) + " * * * *"
	e = xt_func.crontab_replace(const.CRON_SH["ntpd"], run_at)
	if not e[0]:
		ret = False
		emsg.append(e[1])

	return (ret, emsg)
def get(fname=TAG+".txt", fdir=const.CFG_DIR):
	import xte_network
	version_j = xt_func.load_json(const.CFG_DIR+"version.json")[1]
	license_j = xt_func.load_json(const.CFG_DIR+"license.json")[1]
	traffic = _get_summary_traffic()
	detection = _get_summary_detection()
	txt = xt_func.sh(["cat", "/proc/uptime"])[1]
	up_secs = int(txt.split(".")[0]) #Tuncate to integer
	network_c = xte_network.get()[1]

	data = {
		"version": version_j["version"],
		"sn": license_j["sn"],
		"uptime": _calc_uptime(up_secs),
		"connections":xt_func.sudo(["cat", "/proc/sys/net/netfilter/nf_conntrack_count"])[1],
		"cpu":_get_cpu_usage(),
	}
	for pos in const.ALL_POS:
		data[pos] = _get_pos_summary(pos)
		data[pos]["ip"] = _get_wan_address(pos)
		data[pos]["detection"] = detection[pos]
		data[pos]["rx"] = traffic[pos]["rx"]
		data[pos]["tx"] = traffic[pos]["tx"]
		if pos == "lan" or pos == "dmz":
			data[pos]["label"] = "N/A"
		else:
			data[pos]["label"] = network_c[pos]["label"]
	return (True, data)	
def start_traceroute(pos, target):
	dum = const.DUM_IP[pos]
	xt_func.sudo(["rm -f", TRACERT_DONE_FILE, TRACERT_RST_FILE])
	f = open(TRACERT_SH_FILE, "w")
	f.write("#!/bin/sh\n")
	f.write("sudo traceroute -ns "+ dum+ " "+ target+ " >"+ TRACERT_RST_FILE+ " 2>&1\n")
	f.write("touch "+ TRACERT_DONE_FILE + "\n")
	f.close()
	e = xt_func.sh(["sh", TRACERT_SH_FILE], block=False)
	return e
def start_ping(pos, target):
	dum = const.DUM_IP[pos]
	xt_func.sudo(["rm -f", PING_DONE_FILE, PING_RST_FILE])
	f = open(PING_SH_FILE, "w")
	f.write("#!/bin/sh\n")
	f.write("ping -W 3 -c 50 -I "+ dum+ " "+ target+ " >"+ PING_RST_FILE+ " 2>&1\n")
	f.write("touch "+ PING_DONE_FILE + "\n")
	f.close()
	e = xt_func.sh(["sh", PING_SH_FILE], block=False)
	return e
def kill_cmd(cmd):
	e = xt_func.sh(["ps | grep '"+ cmd+ "' | grep -v grep"])
	if not e[0]:
		return (False, [N_("nothing to kill")])

	tok = e[1].strip().split()
	e = xt_func.sudo(["kill", tok[0]])
	if not e[0]:
		return e

	return (True, [N_("kill"), tok[0]])