#!/usr/bin/env python3

from asyncio.log import logger
import paho.mqtt.client as mqtt
from getmac import get_mac_address
import platform
import socket
import re
import subprocess
import os
import json
import sys
import time
import json
import datetime
import ctypes
import getopt
import random
import requests
#import psutil
stats = {}
VERSION = "1.0.28"
curos = platform.system() 
host = platform.node().lower()
print(host)
if curos == "Windows":
    import winreg
def uptime():
     
     try:
         f = open( "/proc/uptime" )
         contents = f.read().split()
         f.close()
     except:
        return "Cannot open uptime file: /proc/uptime"
 
     total_seconds = float(contents[0])
 
     # Helper vars:
     MINUTE  = 60
     HOUR    = MINUTE * 60
     DAY     = HOUR * 24
 
     # Get the days, hours, etc:
     days    = int( total_seconds / DAY )
     hours   = int( ( total_seconds % DAY ) / HOUR )
     minutes = int( ( total_seconds % HOUR ) / MINUTE )
     seconds = int( total_seconds % MINUTE )
 
     # Build up the pretty string (like this: "N days, N hours, N minutes, N seconds")
     string = ""
    #  if days > 0:
    #      string += str(days) + " " + (days == 1 and "d" or "d" ) + ", "
    #  if len(string) > 0 or hours > 0:
    #      string += str(hours) + " " + (hours == 1 and "h" or "h" ) + ", "
    #  if len(string) > 0 or minutes > 0:
    #      string += str(minutes) + " " + (minutes == 1 and "m" or "m" ) + ", "
     if days > 0:
         string += str(days) + " " + (days == 1 and "d" or "d" ) + ", "
     if len(string) > 0 or hours > 0:
         string += str(hours) + ":"
     if len(string) > 0 or minutes > 0:
         string += str(minutes) + ":"
     string += str(seconds)
 
     return string;
  
def writeLog(msg, svr="INFO"):
    ts = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    if curos == "Windows":
        log_path = "c:\Program Files\jaydee\jaydee.log"
    else:
        log_path = "/tmp/mqtt_srv.log"
    f = open(log_path, "a")
    f.write(ts + " | " + svr + " | " + str(msg) + "\n")
    f.close()   

def check_router():
    stats["uptime"] = uptime()
    stats["version"] = VERSION
    stats["status"] = "on"
    cmnd = "crontab -l"
    status, output = subprocess.getstatusoutput(cmnd)
    
    if "#Skynet_banmalware#" in output:
        stats["skynet"] = "On"
    else:
        stats["skynet"] = "Off"
    if "#Diversion_CountAds#" in output:
        stats["diversion"] = "On"
    else:
        stats["diversion"] = "Off"
    
    
    cmnd = "nvram get vpn_client1_state"
    status, output = subprocess.getstatusoutput(cmnd)
    writeLog("VpnClient1 Status : " + str(output))
    stats["vpnclient1"] = "On" if output == "2" else "Off"
    cmnd = "nvram get vpn_client2_state"
    status, output = subprocess.getstatusoutput(cmnd)
    writeLog("VpnClient2 Status : " + str(output))
    stats["vpnclient2"] = "On" if output == "2" else "Off"
    cmnd = "nvram get vpn_server1_state"
    status, output = subprocess.getstatusoutput(cmnd)
    writeLog("VpnServer1 Status : " + str(output))
    stats["vpnserver1"] = "On" if output == "2" else "Off"
    cmnd = "ncat -z 192.168.77.106 25"
    status, output = subprocess.getstatusoutput(cmnd)
    if status == 0:
        stats["mail_nas"] = "available"
    else:
        stats["mail_nas"] = "unavailable"
    cmnd = "ncat -z 192.168.77.246 25"
    status, output = subprocess.getstatusoutput(cmnd)
    if status == 0:
        stats["mail_rasp"] = "available"
    else:
        stats["mail_rasp"] = "unavailable"
    cmnd = "nvram get vts_rulelist"
    status, output = subprocess.getstatusoutput(cmnd)
    rule_data = output.split("<")
    serv_d = {}
    for l in rule_data:
        rul = l.split(">")
        if len(rul) > 3:
            if rul[0] == "HTTPS":
                serv_d[rul[0]] = {"src_port":rul[1],"dest_ip":rul[2],"dest_port":rul[3],"prot":rul[4]}
                stats["serv_dest"] = rul[2]
                break
    #stats["serv_dest"] = json.dumps(serv_d)
    #stats["serv_dest"] = json.dumps(serv_d)
    #out = subprocess.Popen(cmnd.split())
    #status, output = subprocess.getstatusoutput(cmnd)
    
    
    '''
    
    
    print("Getting fw info")
    cmnd = "/root/router_cmd.sh -t firewall -n TOSHIBA-WIFI -m get"
    #out = subprocess.Popen(cmnd.split())
    status, output = subprocess.getstatusoutput(cmnd)
    print(output)
    stats["fw"] = output
    #client.publish("sectorq/systems/router/fw", payload=str(output), qos=0, retain=True)
    print("Getting wifi info")
    cmnd = "/root/router_cmd.sh -t wireless  -m get"
    #out = subprocess.Popen(cmnd.split())
    status, output = subprocess.getstatusoutput(cmnd)
    print(output)
    if output != 'allow':
        output = 'off'
    stats["macfilter"] = output
    # if output == "allow":\
    writeLog("Payload : " + str(json.dumps(stats)))
    '''
    client.publish("home-assistant/router/hwstats", json.dumps(stats), qos=0, retain=True)
    #client.publish("sectorq/systems/router/stats", payload=json.dumps(stats), qos=0, retain=True)
    #else:
    #    client.publish("sectorq/systems/router/macfilter", payload=0, qos=0, retain=True)
                
if host != "router" and host != "nas":
    import psutil
    
    processes = list(p.name() for p in psutil.process_iter())
    # print(processes)
    count = processes.count("mqtt_srv.exe")
    if int(count) >= 3:
        writeLog("script exist")
        sys.exit()
else:
    cmnd = "ps |grep mqtt_srv.py|grep -v grep |wc -l"
    status, output = subprocess.getstatusoutput(cmnd)
    count = output
    if int(count) >= 2:
        writeLog("script exist")
        sys.exit()
# Stops duplicate instance from running
    
writeLog(count)

writeLog("Starting : " + str(VERSION))
writeLog("Getting running proccesses", "DEBUG")


writeLog("done", "DEBUG")

FILE_TIMESTAMP = os.path.getmtime(sys.argv[0])
def get_sys_env(name):
    key = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, r"System\CurrentControlSet\Control\Session Manager\Environment")
    return winreg.QueryValueEx(key, name)[0]

def get_user_env(name):
    key = winreg.CreateKey(winreg.HKEY_CURRENT_USER, r"Environment")
    return winreg.QueryValueEx(key, name)[0]


_PUBLISH = _SETVAR =  False
try:
    opts, args = getopt.getopt(sys.argv[1:], "Sspmt:", ["command=", "help", "output="])
except getopt.GetoptError as err:
    # print help information and exit:
    print(str(err))  # will print something like "option -a not recognized"
    #usage()
    sys.exit(2)
output = None
# QJ : getopts

for o, a in opts:
    if o == "-d":
        _ACTION = True
    elif o in ("-p", "--publish"):
        _PUBLISH = True
    elif o in ("-m", "--publish"):
        _MESSAGE = a
    elif o in ("-t", "--publish"):
        _TOPIC = a
    elif o in ("-S", "--setvar"):    
        _SETVAR = True
        _THR_NAME = sys.argv[2]
        _THR_VAL = sys.argv[3]
    else:
        _WIZZARD = True
MQTT_HOST = "192.168.77.106"
MQTT_PORT = 1883

if _PUBLISH:
    # generate client ID with pub prefix randomly
    #client_id = f'python-mqtt-{random.randint(0, 1000)}'
    client_id = 'python-mqtt-1004'
    username = 'jaydee'
    password = 'jaydee1'

    def connect_mqtt():
        def on_connect(client, userdata, flags, rc):
            if rc == 0:
                print("Connected to MQTT Broker!")
            else:
                print("Failed to connect, return code %d\n", rc)

        client = mqtt.Client(client_id)
        client.username_pw_set(username, password)
        client.on_connect = on_connect
        client.connect(MQTT_HOST, MQTT_PORT)
        return client


    def publish(client):
        result = client.publish(_TOPIC, _MESSAGE)
        # result: [0, 1]
        status = result[0]
        if status == 0:
            print(f"Send `{_MESSAGE}` to topic `{_TOPIC}`")
        else:
            print(f"Failed to send message to topic {_TOPIC}")

    client = connect_mqtt()
    publish(client)
    sys.exit()

if _SETVAR:
    #myCmd = "setx " + _THR_NAME + " " + _THR_VAL + " -m"
    myCmd = "setx " + _THR_NAME + " " + _THR_VAL
    subprocess.Popen(myCmd.split(), shell=True)
    sys.exit()

from ping3 import ping, verbose_ping




'''
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py
pip3 install getmac
pip3 install paho.mqttdasdas
"""

'''

writeLog("Starting daemon in versin : " + VERSION)

VERS = '1.3'
'''
print("pinging")
lala = ping(MQTT_HOST)

connected = 0
while connected == 0:
    if type(lala) == float:
        print("Oleee connected")
        writeLog("Mqtt connected", "INFO")
        connected = 1
    else:
        print("blaaah not connected, waiting...(5)")
        writeLog("blaaah not connected, waiting...(5)")
        time.sleep(5)
    lala = ping(MQTT_HOST)
'''

# Function to display hostname and
# IP address
def get_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        # doesn't even have to be reachable
        s.connect(('192.168.77.1', 1))
        IP = s.getsockname()[0]
    except ValueError:
        IP = '127.0.0.1'
    finally:
        s.close()
    return IP


IP = get_ip()


print("OS : " + curos)
writeLog("OS : " + curos)
if curos != "Windows":
	import autorandr
else:
    import winreg


if host == "raspberrypi":
    mac = str(get_mac_address("eth0"))
elif host == "SERVER":
    mac = str(get_mac_address("enp2s0"))
elif host == "ASUS" and curos != "Windows":
    mac = str(get_mac_address("enp3s0f1"))
elif host == "morefine" and curos != "Windows":
    mac = str(get_mac_address("eno1"))
else:
    mac = str(get_mac_address("Ethernet"))


print("MAC : " + mac)
writeLog("MAC : " + mac)
print("SYSTEM : " + host)
writeLog("SYSTEM : " + host)
print("IP : " + IP)
writeLog("IP : " + IP)

flag_connected = 0
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))
    writeLog("Connected with result code " + str(rc))
    global flag_connected
    flag_connected = 1
    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    topic = "sectorq/systems/" + host.lower()
    print(topic)
    writeLog(topic)
    time.sleep(1)
    client.publish("sectorq/status", payload="{'action':'connect', 'system':'" + host.lower() + "', 'ip': '" + IP + "', 'mac':'" + mac + "', 'ver':'" + VERS + "'}", qos=0, retain=False)
    client.publish("sectorq/systems/" + host.lower() + "/stat", payload="on", qos=0, retain=True)
    if host.lower() == "router":
        check_router()
        
    if host.lower() == "nas":
        print("Getting VM info")
        
        cmnd = "/share/ZFS532_DATA/.qpkg/QKVM/usr/bin/virsh list --all"
        print(cmnd)
        status, output = subprocess.getstatusoutput(cmnd)
        l = 1 
        lines = output.splitlines()
        VMS = {}
        for i in lines:
            l = l + 1
            if l < 4:
                continue
            line = re.split(r" {2,}", i)
            print(str(line[0].strip()) + " " + str(line[1].strip()) + " " + str(line[2].strip()))
            VMS[str(line[1].strip())] = str(line[2].strip())
            
            
        
        for m in VMS:
        
            cmnd = "/share/ZFS532_DATA/.qpkg/QKVM/usr/bin/virsh  domstate " + m
            #out = subprocess.Popen(cmnd.split())
            print(cmnd)
            status, output = subprocess.getstatusoutput(cmnd)
            print(output)
            if output.strip() ==  "running":
                client.publish("sectorq/systems/nas/" + m, payload=1, qos=0, retain=True)
            else:
                client.publish("sectorq/systems/nas/" + m, payload=0, qos=0, retain=True)
 

    client.subscribe(topic)

def on_disconnect(client, userdata, rc):
    print("disconnecting reason  "  +str(rc))
    writeLog("disconnecting reason  "  +str(rc))
    client.connected_flag=False
    client.disconnect_flag=True
    global flag_connected
    flag_connected = 0


# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    print(msg.topic)
    print(msg.payload)
    myObj = msg.payload.decode('utf-8')
    # command = re.sub(r"^b\'|\'$", "", str(msg.payload))
    # command = json.loads(msg.payload.decode("utf-8"))
    try:
        myObj = json.loads(msg.payload)
        try:
            writeLog(myObj["action"])
            print(myObj["action"])
        except:
            print("Action not set")
            writeLog("Action not set", "WARNING")
        
        try:
            print(myObj["cmd"])
            writeLog(myObj["cmd"])
        except:
            print("Cmd not set")
            writeLog("Cmd not set", "WARNING")
        
        try:
            print(myObj["target"])
            writeLog(myObj["target"])
        except:
            print("Target Not Set")
            writeLog("Target Not Set", "WARNING")
        try:
            print(myObj["status"])
            writeLog(myObj["status"])
        except:
            print("Status Not Set")
            writeLog("Status Not Set")

        try:
            print(myObj["command"])
            writeLog(myObj["command"])
        except:
            print("Command Not Set")
            writeLog("Command Not Set")
        
        try:
            print(myObj["cmd_line"])
            writeLog(myObj["cmd_line"])
        except:
            print("Cmd_line Not Set")
            writeLog("Cmd_line Not Set")


        if myObj["cmd"] == "command":

            print("Executing " + myObj["cmd_line"])
            writeLog("Executing " + myObj["cmd_line"])
            #os.system('start /b "' + myObj["cmd_line"] + '"')
            try:
                subprocess.Popen(myObj["cmd_line"].split(), shell=True)
                #subprocess.Popen(myObj["cmd_line"].split())
                # ctypes.windll.user32.MessageBoxW(0, myObj["cmd_line"], "Executed", 64)
            except:
                ctypes.windll.user32.MessageBoxW(0, "Your text", "Your title", 16)
            print("Executed " + myObj["cmd_line"])
            writeLog("Executed " + myObj["cmd_line"])
        
        if myObj["cmd"] == "nas_cmd":
            print("Executing NAS")
            #cmnd = "/share/ZFS530_DATA/.qpkg/QKVM/usr/bin/virsh  domstate " + str(myObj["target"])
            cmnd = "/share/ZFS532_DATA/.qpkg/QKVM/usr/bin/virsh domstate " + str(myObj["target"])
            print(cmnd)
            status, output = subprocess.getstatusoutput(cmnd)
            print(output)
            cmd_type = myObj["command"]
            if myObj["command"] == "start":
                if output.strip() == "paused":
                    print("System suspended")
                    cmd_type = "resume"
                else:
                    print("System Off")
                    cmd_type = "start"
            if myObj["command"] == "suspend":
                cmd_type = "shutdown"
                
            
            cmnd = "/share/ZFS532_DATA/.qpkg/QKVM/usr/bin/virsh " + cmd_type + " " + str(myObj["target"])
            subprocess.Popen(cmnd.split())
            print(cmnd)
            if myObj["command"] == "start":
                try:
                    print("sending")
                    client.publish("sectorq/systems/nas/" + str(myObj["target"]), payload=1, qos=0, retain=False)
                except:
                    print("failed to execute!")
                    client.publish("sectorq/systems/nas/" + str(myObj["target"]), payload="failed", qos=0, retain=False)
            else:
                try:
                    print("sending")
                    client.publish("sectorq/systems/nas/" + str(myObj["target"]), payload=0, qos=0, retain=False)
                except:
                    print("failed to execute!")
                    client.publish("sectorq/systems/nas/" + str(myObj["target"]), payload="failed", qos=0, retain=False)
                
                
        if myObj["cmd"] == "distrib":
            print("distributin313g")
            # os.startfile(sys.argv[0])
            #sys.exit()
            subprocess.Popen(['/bin/systemctl', 'restart', 'mqtt'])
        
        if myObj["cmd"] == "uci":
            print("uci1")
            print("Executing " + myObj["cmd_line"])
            writeLog("Executing " + myObj["cmd_line"])

            if myObj["cmd_line"] == "wireless1":
                cmnd = "/root/router_cmd.sh -t wireless -v 1 -m set"
                try:
                    subprocess.Popen(cmnd.split())
                    print("sending")
                    stats["macfilter"] = "allow"
                    client.publish("sectorq/systems/router/stats", payload=json.dumps(stats), qos=0, retain=False)
                    writeLog("Payload : " + json.dumps(stats))
                except:
                    print("failed to execute!")
                    client.publish("sectorq/systems/router/stats", payload="failed", qos=0, retain=False)
                
            elif myObj["cmd_line"] == "wireless0":
                cmnd = "/root/router_cmd.sh -t wireless -v 0 -m set"
                try:
                    subprocess.Popen(cmnd.split())
                    print("sending")
                    stats["macfilter"] = "off"
                    client.publish("sectorq/systems/router/stats", payload=json.dumps(stats), qos=0, retain=False)
                    writeLog("Payload : " + json.dumps(stats))
                except:
                    print("failed to execute!")
                    client.publish("sectorq/systems/router/stats", payload="failed", qos=0, retain=False)
            elif myObj["cmd_line"] == "fw0":
                cmnd = "/root/router_cmd.sh -t firewall -n TOSHIBA-WIFI -p enabled -v 0 -m set"
                try:
                    subprocess.Popen(cmnd.split())
                    print("sending")
                    stats["fw"] = 0
                    client.publish("sectorq/systems/router/stats", payload=json.dumps(stats), qos=0, retain=False)
                    writeLog("Payload : " + json.dumps(stats))
                except:
                    print("failed to execute!")
                    client.publish("sectorq/systems/router/stats", payload="failed", qos=0, retain=False)
            elif myObj["cmd_line"] == "fw1":
                cmnd = "/root/router_cmd.sh -t firewall -n TOSHIBA-WIFI -p enabled -v 1  -m set"
                try:
                #subprocess.Popen(myObj["cmd_line"].split(), shell=True)
                    subprocess.Popen(cmnd.split())
                # ctypes.windll.user32.MessageBoxW(0, myObj["cmd_line"], "Executed", 64)
                    print("sending")
                    stats["fw"] = 1
                    client.publish("sectorq/systems/router/stats", payload=json.dumps(stats), qos=0, retain=False)
                    writeLog("Payload : " + json.dumps(stats))
                except:
                    print("failed to execute!")
                    client.publish("sectorq/systems/router/stats", payload="failed", qos=0, retain=False)
            elif myObj["cmd_line"] == "openvpn":
                cmnd = "service {}".format(myObj["target"])
                print(cmnd)
                status, output = subprocess.getstatusoutput(cmnd)
                
            elif myObj["cmd_line"] == "serv_dest":
                writeLog("Payload111111 : " + myObj["target"].lower())
                
                cmnd = "nvram get vts_rulelist"
                status, output = subprocess.getstatusoutput(cmnd)
                rule_data = output.split("<")
                serv_d = {}
                writeLog("Payload111112")
                for l in rule_data:
                    rul = l.split(">")
                    if len(rul) > 3:
                        serv_d[rul[0]] = {"src_port":rul[1],"dest_ip":rul[2],"dest_port":rul[3],"prot":rul[4]}
                        stats["serv_dest"] = rul[2]
                writeLog("Payload111113")
                rules = {"HTTPS":{"dest_ip":"192.168.77.106","src_port":443,"dest_port":443,"prot":"TCP"},
                         "HTTP":{"dest_ip":"192.168.77.106","src_port":80,"dest_port":80,"prot":"TCP"},
                         "EMAIL_25":{"dest_ip":"192.168.77.106","src_port":25,"dest_port":25,"prot":"TCP"},
                         "EMAIL_465":{"dest_ip":"192.168.77.106","src_port":465,"dest_port":465,"prot":"TCP"},
                         "EMAIL_993":{"dest_ip":"192.168.77.106","src_port":993,"dest_port":993,"prot":"TCP"},
                         "EMAIL_995":{"dest_ip":"192.168.77.106","src_port":995,"dest_port":995,"prot":"TCP"},
                         "EMAIL_587":{"dest_ip":"192.168.77.106","src_port":587,"dest_port":587,"prot":"TCP"},
                         "EMAIL_143":{"dest_ip":"192.168.77.106","src_port":143,"dest_port":143,"prot":"TCP"}}
                writeLog("Payload1111135")
                print(json.dumps(serv_d))
                for r in rules:
                    print(r)
                    try:
                        serv_d[r]["dest_ip"] = myObj["target"]
                    except:
                        serv_d[r] = rules[r]
                        
                lala = []
                for sr in serv_d:
                    lala.append("{}>{}>{}>{}>{}>".format(sr,serv_d[sr]["src_port"],serv_d[sr]["dest_ip"],serv_d[sr]["dest_port"],serv_d[sr]["prot"]))
                la = "<".join(lala)
                la = "<{}".format(la)
                print(la)
                cmnd = "nvram set vts_rulelist=\"{}\"".format(la)
                print(cmnd)
                status, output = subprocess.getstatusoutput(cmnd)
                cmnd = "nvram commit"
                status, output = subprocess.getstatusoutput(cmnd)
                cmnd = "service restart_firewall"
                status, output = subprocess.getstatusoutput(cmnd)
                writeLog("Payload111114")   
                writeLog(output)
                print(json.dumps(serv_d))
                '''
                if myObj["target"].lower() == "192.168.77.246":
                    dest_ip = "192.168.77.246"
                elif myObj["target"].lower() == "192.168.77.106":
                    dest_ip = "192.168.77.106"
                    
                    
                    
                
                RULES = ["EMAIL993", "EMAIL995", "EMAIL143", "EMAIL25", "EMAIL993", "EMAIL465", "HTTPS", "HTTP"]
                for i in RULES:
                    cmnd = "uci set firewall.{}.dest_ip={}".format(i,dest_ip)
                    writeLog(cmnd)
                    subprocess.Popen(cmnd.split())
                    
                #cmnd = "uci set dhcp.@dnsmasq[0].address=/mqtt_broker/" + dest_ip
                #writeLog(cmnd)
                #subprocess.Popen(cmnd.split())
                time.sleep(1)
                cmnd = "uci commit"
                
                subprocess.Popen(cmnd.split())
                
                writeLog("Starting " + myObj["target"].lower())
                if myObj["target"].lower() == "192.168.77.246":
                    dest_ip = "192.168.77.246"
                    
                    
                    cmnd = "ssh root@192.168.77.246 'docker start mailu_resolver_1 mailu_redis_1  mailu_front_1 mailu_antispam_1 mailu_imap_1 mailu_admin_1 mailu_smtp_1 mailu_webmail_1  watchtower_watchtower_1 nginx-proxy-manager_db_1 nginx-proxy-manager_app_1 HomeAssistant webhub_client_1 dockermon_docker_mon_1 mosquitto_mosquitto_1 node-red_node-red_1 nextcloud_db_1 nextcloud_app_1'"
                    status, output = subprocess.getstatusoutput(cmnd)
                elif myObj["target"].lower() == "192.168.77.106":
                    dest_ip = "192.168.77.106"
                    cmnd = "ssh root@192.168.77.246 'docker stop mailu_resolver_1 mailu_redis_1  mailu_front_1 mailu_antispam_1 mailu_imap_1 mailu_admin_1 mailu_smtp_1 mailu_webmail_1  watchtower_watchtower_1 nginx-proxy-manager_db_1 nginx-proxy-manager_app_1 HomeAssistant webhub_client_1 dockermon_docker_mon_1 mosquitto_mosquitto_1 node-red_node-red_1 nextcloud_db_1 nextcloud_app_1'"
                    status, output = subprocess.getstatusoutput(cmnd)
                time.sleep(1)
                cmnd = "/etc/init.d/firewall restart"
                subprocess.Popen(cmnd.split())
                #cmnd = "/etc/init.d/dnsmasq restart"
                #subprocess.Popen(cmnd.split())
                writeLog("reconfigure iot")
                MQTT_BROKER = dest_ip
                MQTT_USER = "jaydee"
                MQTT_PASS = "jaydee1"
                
                cmnd = "nmap -sP 192.168.77.*|grep \"Nmap scan report\"|egrep -o \"[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\""
                #print(cmnd)
                status, output = subprocess.getstatusoutput(cmnd)

                # print(output)

                ips = output.splitlines()
                tasm_data = {}
                for sys_ip in ips:
                    # print("Thsis is ip : " + sys_ip)
                    cmnd = "nmap  " + sys_ip + " -p80|grep \"80/tcp open  http\""
                    status, output = subprocess.getstatusoutput(cmnd)
                    # print("status of 80 : " + str(status))
                    if status == 0:
                        try:
                        # url = "http://" + sys_ip + "/cm?user=admin&password=l4c1j4yd33Du5l0&cmnd=STATUS+5"
                        
                            url = "http://" + sys_ip + "/cm?cmnd=Backlog%20MqttHost%20" + MQTT_BROKER + "%3BMqttUser%20" + MQTT_USER + "%3BMqttPassword%20" + MQTT_PASS
                            print(url)
                            requests.get(url)
                            
                        except:
                            #print(sys_ip + " : Not a tasmota!")
                            pass
                    else:
                        #print(sys_ip + " : Not a listening")
                        pass

                
                
                time.sleep(1)
                cmnd = "sed -i 's/^MQTT_HOST = .*/MQTT_HOST = \"" + dest_ip + "\"/' /root/mqtt_srv.py"
                writeLog(cmnd)
                status, output = subprocess.getstatusoutput(cmnd)
            #for i in ;do uci set firewall.${i}.dest_ip=192.168.77.246;done;uci set firewall.HTTPS.dest_port='443';uci set firewall.HTTP.dest_port='80' ;uci commit;/etc/init.d/firewall restart
            else:
                pass
                #cmnd = "/root/router_cmd.sh -t wireless -v 0"
            
           
            print("Executed " + cmnd)
            writeLog("Executed " + cmnd)
            '''
            
            
        if myObj["cmd"] == "banip":
            if myObj["status"] == "ban":
                cmnd = "echo " + str(myObj["target"]) + " >> /etc/banip/banip.blacklist; /etc/init.d/banip refresh"
            elif myObj["status"] == "enable":
                cmnd = "/etc/init.d/banip resume"
                stats["banip"] = "enabled"
            elif myObj["status"] == "disable":
                cmnd = "/etc/init.d/banip suspend"
                stats["banip"] = "paused"
            writeLog(cmnd)
            status, output = subprocess.getstatusoutput(cmnd)
            
            client.publish("sectorq/systems/router/stats", payload=json.dumps(stats), qos=0, retain=True)
    
        if myObj["cmd"] == "vnc":
            print(myObj["target"])
            writeLog(myObj["target"])
            
            # os.startfile(sys.argv[0])
            #sys.exit()
            myCmd = 'c:\\Program Files\\RealVNC\\VNC Viewer\\vncviewer.exe C:\\Users\\jaydee\\' + myObj["target"].upper() + '.vnc'
            print(myCmd)
            writeLog(myCmd)
            subprocess.Popen(myCmd.split())
        if myObj["cmd"] == "getstats":
            print("lalaa1")
            try:
                client.publish("sectorq/monitor/" + host.lower(), payload="{\"mb_temp\":" + get_user_env('mb_temp') + ",\"mem_usage\":" + get_user_env('mem_usage') + ",\"cpu_temp\":" + get_user_env('cpu_temp') + ",\"cpu_usage\":" + get_user_env('cpu_usage') + ",\"gpu_temp\":" + get_user_env('gpu_temp') + ",\"gpu_usage\":" + get_user_env('gpu_usage') + "}", qos=0, retain=False)
                print("ok")
            except:
                print("failed")
                client.publish("sectorq/monitor/" + host.lower(), payload="{\"mb_temp\":0,\"mem_usage\":0,\"cpu_temp\":0,\"cpu_usage\":0,\"gpu_temp\":0,\"gpu_usage\":0}", qos=0, retain=False)

            print("lalaa2")
            
        if myObj["cmd"] == "display":
            if curos == "Windows1":
                # os.startfile(sys.argv[0])
                #sys.exit()
                #print("reconfigure")
                myCmd = 'MonitorSwitcher.exe -load:' + myObj["target"] + '.xml'
                writeLog(myCmd)
                #writeLog(os.path.realpath(__file__))
                print("lalaa2")
                #subprocess.Popen(r'"{}"'.format(myCmd), shell=True)
                print("lalaa3")
                subprocess.Popen(myCmd.split(), shell=True,cwd=r'c:\Progra~1\jaydee')
            else:
                '''
                myCmd = ""
                if myObj["target"] == "mid":
                    myCmd = "xrandr --output HDMI-2 --primary --auto --mode 1920x1080 --output DVI-I-2-1 --off --output HDMI-1 --off --output eDP-1 --off"
                elif myObj["target"] == "all":    
                    myCmd = "xrandr --output HDMI-2 --primary --auto --mode 1920x1080 --output DVI-I-2-1 --auto --above HDMI-2 --mode 1920x1080 --output HDMI-1 --auto --left-of HDMI-2 --mode 1920x1080 --output eDP-1 --auto --right-of HDMI-2 --mode 1920x1080"
                elif myObj["target"] == "midleft":    
                    myCmd = "xrandr --output HDMI-2 --primary --auto --mode 1920x1080 --output DVI-I-2-1 --off --output HDMI-1 --auto --left-of HDMI-2 --mode 1920x1080 --output eDP-1 --off"
                elif myObj["target"] == "midtop":    
                    myCmd = "xrandr --output HDMI-2 --primary --auto --mode 1920x1080 --output DVI-I-2-1 --auto --above HDMI-2 --mode 1920x1080 --output HDMI-1 --off --output eDP-1 --off"
                elif myObj["target"] == "midleftbuild":    
                    myCmd = "xrandr --output HDMI-2 --primary --auto --mode 1920x1080 --output DVI-I-2-1 --off --output HDMI-1 --auto --left-of HDMI-2 --mode 1920x1080 --output eDP-1 --auto --right-of HDMI-2 --mode 1920x1080"   
                elif myObj["target"] == "midbuild":    
                    myCmd = "xrandr --output HDMI-2 --primary --auto --mode 1920x1080 --output DVI-I-2-1 --off --output HDMI-1 --off --output eDP-1 --auto --right-of HDMI-2 --mode 1920x1080"
                elif myObj["target"] == "midlefttop":    
                    myCmd = "xrandr --output HDMI-2 --primary --auto --mode 1920x1080 --output DVI-I-2-1 --auto --above HDMI-2 --mode 1920x1080 --output HDMI-1 --auto --left-of HDMI-2 --mode 1920x1080 --output eDP-1 --off"
                else:
                    pass    
                
                if myCmd != "":
                    print(myCmd)
                    subprocess.Popen(myCmd.split())
                '''
                myCmd = ""
                writeLog(myObj["target"])
                if curos == "Windows":

                    myCmd = "DisplayFusionCommand.exe -monitorloadprofile {}".format(myObj["target"])

                else:
                    '''
                    mon1 = "HDMI-1-1"
                    mon2 = "HDMI-1-2"
                    mon3 = "DVI-I-2-1"
                    mon4 = "eDP-1-1"
                    '''
                    right = ["HDMI-A-0", "1920x1080"]
                    tleft = ["HDMI-A-0", "1920x1080"]
                    tright = ["DVI-I-1-1", "1920x1080"]
                    left = ["DisplayPort-0", "2560x1440"]
                    mid = ["DisplayPort-1", "3440x1440"]
                    
                    #xrandr --output DisplayPort-1 --primary --auto --mode 3440x1440 --output HDMI-A-0 --auto --left-of DVI-I-1-1 --mode 1920x1080 --output DisplayPort-0 --auto --left-of DisplayPort-1 --mode 2560x1440 --output DVI-I-1-1 --above DisplayPort-1 --mode 1920x1080
                    if myObj["target"] == "mid":
                        myCmd = f"xrandr --output {mid[0]} --primary --auto --mode {mid[1]}  --output {left[0]} --off --output {tleft[0]} --off --output {tright[0]} --off"
                    elif myObj["target"] == "left":    
                        myCmd = f"xrandr --output {left[0]} --primary --auto --mode {left[1]} --output {mid[0]} --off --output {tleft[0]} --off --output {tright[0]} --off"                      
                    elif myObj["target"] == "all":
                        myCmd = f"xrandr --output {mid[0]}  --primary --auto --mode {mid[1]} --pos 0x0 --output {tleft[0]} --auto --pos -1920x-1080 --mode {tleft[1]} --output {left[0]} --auto --left-of {mid[0]} --mode {left[1]} --output {tright[0]} --above {mid[0]} --mode {tright[1]}"
                        #myCmd = f"xrandr --output {mid[0]} --primary --auto --mode {mid[1]} --output {right[0]} --auto --right-of {mid[0]} --mode {right[1]}  --output {left[0]} --auto --left-of {mid[0]} --mode {left[1]}"
                    elif myObj["target"] == "midleft":    
                        myCmd = f"xrandr --output {mid[0]} --primary --auto --mode {mid[1]} --output {tleft[0]} --off --output {left[0]} --auto --left-of {mid[0]} --mode {left[1]} --output {tright[0]} --off"
                    elif myObj["target"] == "midtop":    
                        myCmd = f"xrandr --output {mid[0]} --primary --auto --mode {mid[1]} --output {tright[0]} --auto --above {mid[0]} --mode {tright[1]} --output {left[0]} --off --output {tleft[0]} --off" 
                    elif myObj["target"] == "midlefttleft":    
                        myCmd = f"xrandr --output {mid[0]} --primary --auto --mode {mid[1]} --pos 0x0 --output {tright[0]} --off --output {left[0]} --auto --left-of {mid[0]} --mode {left[1]} --output {tleft[0]} --auto --pos -1920x-1080 --mode {tleft[1]}"
                    elif myObj["target"] == "lefttlefttright":    
                        myCmd = f"xrandr --output {mid[0]} --off --output {tleft[0]} --auto --pos 640x-1080 --mode {tright[1]} --output {left[0]} --primary --auto --mode {left[1]} --pos 0x0 --output {tright[0]} --right-of {tleft[0]} --mode {tright[1]}" 
                    elif myObj["target"] == "lefttleft":    
                        myCmd = f"xrandr --output {mid[0]} --off --output {tleft[0]} --auto --pos 640x-1080 --mode {tright[1]} --output {left[0]} --primary --auto --mode {left[1]} --pos 0x0 --output {tright[0]} --off" 
                    
                    else:
                        pass    
                    
                writeLog(myCmd)
                if myCmd != "":
                    print(myCmd)
                    writeLog("Executing : {myCmd}")
                    #subprocess.Popen(myCmd.split())
                    status, output = subprocess.getstatusoutput(myCmd)
                    writeLog(output)
                    writeLog(status)
        if myObj["cmd"] == "display2":
            # os.startfile(sys.argv[0])
            #sys.exit()
            #print("reconfigure")
            subprocess.Popen(['MultiMonitorTool.exe', '/SaveConfig', 'c:\\Program Files\\jaydee\\switcher.cfg']) 
            myCmd = "powershell switcher.ps1 " + str(myObj["target"]) + " " + str(myObj["status"])
            writeLog(myCmd)
            subprocess.Popen(myCmd.split())
            time.sleep(1)
            subprocess.Popen(['MultiMonitorTool.exe', '/LoadConfig', 'c:\\Program Files\\jaydee\\switcher.cfg']) 
            client.publish("sectorq/feedback", payload='{"action":"resp", "source":"ASUS", "dev":{"display' + str(myObj["target"]) + '":'+ str(myObj["status"]) +'} }'  , qos=0, retain=False)
        if myObj["cmd"] == "displ":
            print("Display")
            # os.startfile(sys.argv[0])
            #sys.exit()
            subprocess.Popen(['/usr/bin/xrandr', '--output', 'HDMI-1-1', '--off'])

        if myObj["cmd"] == "xrandr":
            if curos == "Windows":
                subprocess.Popen(['MultiMonitorTool.exe', '/LoadConfig', 'c:\\Program Files\\jaydee\\all_on.cfg']) 
            else:
                print("Display")
                # os.startfile(sys.argv[0])
                #sys.exit()
                os.system("export DISPLAY=:0")
                subprocess.Popen(['/usr/bin/xrandr'])

        if myObj["cmd"] == "suspend":
            print("suspending")
            if curos == "Windows":
                if host == "amd" or host == "amd1":
                    os.system("shutdown /s /t 1")
                else:
                    os.system("rundll32.exe powrprof.dll,SetSuspendState 0,1,0")
                #cmnd = "psshutdown -d -t 1"
                writeLog(cmnd)
                #status, output = subprocess.getstatusoutput(cmnd)
                #subprocess.Popen(["psshutdown", "-d", "-t", "1"])
                #writeLog(output)
            else:
                if host == "nas" or host == "octopi":
                    subprocess.Popen(["/sbin/poweroff"])
                elif host == "openmediavault" or  host == "omv" or  host == "amd" or  host == "ryzen":
                    subprocess.Popen(["poweroff"])
                elif host == "amd" or  host == "ryzen":
                    subprocess.Popen(["systemctl suspend"])
                
                else:
                    #subprocess.Popen(["/bin/systemctl", "suspend", "-i"])
                    #subprocess.Popen(["sudo", "pm-suspend"])
                    cmnd  = "pm-suspend"
                    status, output = subprocess.getstatusoutput(cmnd)
                    print(output)
                    print(status)
        if myObj["cmd"] == "stats":
            grep = subprocess.Popen(['grep', 'cpu', '/proc/stat'],
                                    stdout=subprocess.PIPE,
                                    )

            awk = subprocess.Popen(['awk', '{print ($13-$2+$15-$4)*100/($13-$2+$15-$4+$16-$5)}'],
                                stdin=grep.stdout,
                                stdout=subprocess.PIPE,
                                )

            # cat <(grep 'cpu ' /proc/stat) <(sleep 1 && grep 'cpu ' /proc/stat) | awk -v RS="" '{print ($13-$2+$15-$4)*100/($13-$2+$15-$4+$16-$5)}'

            end_of_pipe = awk.stdout

            for line in end_of_pipe:
                # print(line.strip())
                # usage = re.sub(r"^b\'|\'$", "", (line.strip()))
                cpu = round(float(line.strip().decode("utf-8")))
            free = subprocess.Popen(['free'],
                                    stdout=subprocess.PIPE,
                                    )

            grep = subprocess.Popen(['grep', 'Mem'],
                                    stdout=subprocess.PIPE,
                                    stdin=free.stdout,
                                    )

            awk = subprocess.Popen(['awk', '{print $3/$2 * 100.0}'],
                                stdin=grep.stdout,
                                stdout=subprocess.PIPE,
                                )

            end_of_pipe = awk.stdout

            for line in end_of_pipe:
                # print(line.strip())
                # mem = re.sub(r"^b\'|\'$", "", (line.strip()))
                mem = round(float(line.strip().decode("utf-8")))
            # mem = re.sub(r"^b\'|\'$", "", mem)
            # cpu = re.sub(r"^b\'|\'$", "", cpu)
            # print(mem)
            jn = {"cpu": cpu, "mem": mem}
            jn = json.dumps(jn)
            client.publish("sectorq/status/" + host, payload=jn, qos=0, retain=False)
    except:
        print("not a json!")

client = mqtt.Client()
payload = '{"status": "off"}'
client.username_pw_set("jaydee", password="jaydee1")
client.will_set("home-assistant/" + host.lower() + "/hwstats", payload=payload, qos=0, retain=True)
client.on_connect = on_connect
client.on_message = on_message
writeLog(MQTT_HOST)
connected = False
while not connected:
    try:
        client.connect(MQTT_HOST, MQTT_PORT, 25)
        connected = True
    except:
        writeLog("Failed to connect repeating...")
        time.sleep(10)
        

# client.publish("sectorq/status", payload="{'action':'connect', 'system':'" + host + "', 'ip': '" + IP + "', 'mac':'" + mac + "', 'ver':'?'}", qos=0, retain=False)


# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.

def checkIfProcessRunning(processName):
    '''
    Check if there is any running process that contains the given name processName.
    '''
    #Iterate over the all the running process
    for proc in psutil.process_iter():
        try:
            # Check if process name contains the given name string.
            if processName.lower() in proc.name().lower():
                return True
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass
    return False;



if curos == "Windows":
    print("WINDOWS")
    #client.loop_forever()
    client.loop_start()
    NEXT_CHECK = 0
    while True:
        print("Version: {}".format(VERSION))
        time.sleep(5)
        try:
            mtime = os.path.getmtime(sys.argv[0])
        except OSError:
            mtime = 0
        print(mtime)
        if NEXT_CHECK < int(time.time()):
            NEXT_CHECK = int(time.time()) + 10
            writeLog("Blalala : Next : " + str(NEXT_CHECK))
            if curos == "Windows":
                if checkIfProcessRunning("aida64.exe"):
                    aide_refs = {
                        'TPCHDIO':"MB_TEMP",
                        'TCPU':'CPU_TEMP',
                        'SMEMUTI': 'MEM_UTIL',
                        'SVIRTMEMUTI': 'VMEM_UTIL',
                        'SCPUUTI': 'CPU_UTIL',
                        'FCPU': 'FAN_CPU',
                        'TGPU1DIO': 'GPU_TEMP',
                        'SGPU1BIUTI': 'GPU_UTIL',
                        'TMOBO':'MB_TEMP'
                    }
                    #ks = ["TCPU", "TPCHDIO", "SMEMUTI", "SVIRTMEMUTI", "SCPUUTI", "FCPU", "TGPU1DIO", "SGPU1BIUTI"]
                    
                    
                    
                    
                    path = winreg.HKEY_CURRENT_USER
                    try:
                        key = winreg.OpenKeyEx(path, r"SOFTWARE\\FinalWire\\AIDA64\\SensorValues")
                        results = {}
                        results["status"] = "on"
                        for k in aide_refs:
                            k2 = "Value." + str(k)
                            try:
                                value = winreg.QueryValueEx(key,k2)
                                print("{} : {}".format(k, value[0]))
                                results[aide_refs[k]] = value[0]
                            except:
                                pass
                    except:
                        print("aida initializing...")
                        results = {"status":"init"}
                    
                    
                else:
                    print("CPU Cnt : {}".format(psutil.cpu_count()))
                    print(psutil.virtual_memory())
                    cpu_usage = psutil.cpu_percent(interval=None)
                    swap_data = psutil.swap_memory()
                    print("CPU : {}".format(cpu_usage))
                    mem_data = psutil.virtual_memory()
                    print(mem_data)
                    print(swap_data)
                    print("MEM : {}".format(mem_data.percent))
                    print(psutil.getloadavg())
                    #lodctr /R
                    try:     
                        print(psutil.sensors_temperatures())
                    except:
                        pass
                    try:
                        print(psutil.sensors_fans())
                    except:
                        pass
                    results = {"status":"on","version":VERSION,"MB_TEMP":"NA", "MEM_UTIL":str(mem_data.percent), "CPU_TEMP":"NA", "FAN_CPU":"NA",  "VMEM_UTIL":swap_data.percent, "CPU_UTIL":cpu_usage, "GPU_TEMP":"NA", "GPU_UTIL":"NA"}
                print(json.dumps(results))
                r = json.dumps(results)
                #client.publish("home-assistant/" + host + "/hwstats", payload='{"TPCHDIO":"' + str(results["TPCHDIO"]) + '", "SMEMUTI":"' + str(results["SMEMUTI"]) + '", "TCPU":"' + str(results["TCPU"]) + '", "TGPU1DIO":"' + str(results["TGPU1DIO"]) + '", "SGPU1BIUTI":"' + str(results["SGPU1BIUTI"]) + '", "FCPU":"' + str(results["FCPU"]) + '", "SVIRTMEMUTI":"' + str(results["SVIRTMEMUTI"]) + '", "SCPUUTI":"' + str(results["SCPUUTI"]) + '"}', qos=0, retain=False)
                client.publish("home-assistant/" + host + "/hwstats", payload=r, qos=0, retain=False)
                client.publish("sectorq/systems/" + host.lower() + "/stat", payload="on", qos=0, retain=True)
                #print(json.dumps(stats))
                #writeLog(json.dumps(stats))
else:
    print("Linux")
    client.loop_start()

    NEXT_CHECK = 0
    while True:
        #print(VERSION)
        time.sleep(5)
        try:
            mtime = os.path.getmtime(sys.argv[0])
        except OSError:
            mtime = 0
        #print(mtime)
        if NEXT_CHECK < int(time.time()):
            NEXT_CHECK = int(time.time()) + 20
            writeLog("Blalala : Next : " + str(NEXT_CHECK))

            if host.lower() == "asus" or host.lower() == "morefine" or host.lower() == "ryzen":
                writeLog("Blalala : AAA")
                print(psutil.sensors_temperatures())
                #print(psutil.sensors_fans())
                sences = psutil.sensors_temperatures()
                print("SENCES")
                print(sences)
                print("#"*40)
                try:
                    cpu_data = sences["coretemp"][0]
                except:
                    try:
                        cpu_data = sences["k10temp"][0]
                    except:
                        cpu_data = "None"
                writeLog(cpu_data)
                print("CPUDATA")
                print(cpu_data)
                print("#"*40)
                print("MBDATA")
                try:
                    mb_data = sences["acpitz"][0]
                    print(mb_data)
                    print(mb_data.current)
                    mb_data = mb_data.current
                except:
                    mb_data = 0
                
                
                print("#"*40)
                
                
                try:
                    print(psutil.sensors_fans())
                    fan_data = psutil.sensors_fans()["asus"][0].current
                except:
                    fan_data = "None"
                mem_data = psutil.virtual_memory()
                swap_data = psutil.swap_memory()
                #cpu_usage = psutil.cpu_percent(interval=1)
                load1, load5, load15 = psutil.getloadavg()
                cpu_usage = round((load1/os.cpu_count()) * 100, 1)
                
                print(mem_data)
                print(mem_data.percent)
                print(psutil.disk_usage('/'))
                #print(psutil.virtual_memory())
                #print(dict(psutil.virtual_memory()._asdict()))
                #cmnd = "sensors -j|grep -v \"Can't read\""
                #status, output = subprocess.getstatusoutput(cmnd)
                #print(output)
                #print(type(output))
                #jn1 = json.loads(output)
                
                #print(str(jn1["coretemp-isa-0000"]["Package id 0"]["temp1_input"]))
                #print(str(jn1["asus-isa-0000"]["cpu_fan"]["fan1_input"]))
                #client.publish("sectorq/monitor/" + host.lower(), payload="{\"mb_temp\":0,\"mem_usage\":0,\"cpu_temp\":0,\"cpu_usage\":0,\"gpu_temp\":0,\"gpu_usage\":0}", qos=0, retain=False)
                writeLog('{"status":"on", "version":"' + VERSION + '","TCPU":"NA", "MB_TEMP":' + str(mb_data) + ', "MEM_UTIL":' + str(mem_data.percent) + ', "CPU_TEMP":' + str(cpu_data.current) + ', "GPU_TEMP":0, "GPU_UTIL":0, "FAN_CPU":"' + str(fan_data) + '", "VMEM_UTIL":' + str(swap_data.percent) + ', "CPU_UTIL":' + str(cpu_usage) + '}')
                client.publish("home-assistant/" + host + "/hwstats", payload='{"status":"on", "version":"' + VERSION + '","TCPU":"NA", "MB_TEMP":' + str(mb_data) + ', "MEM_UTIL":' + str(mem_data.percent) + ', "CPU_TEMP":' + str(cpu_data.current) + ', "GPU_TEMP":0, "GPU_UTIL":0, "FAN_CPU":"' + str(fan_data) + '", "VMEM_UTIL":' + str(swap_data.percent) + ', "CPU_UTIL":' + str(cpu_usage) + '}', qos=0, retain=False)
                client.publish("sectorq/systems/" + host.lower() + "/stat", payload="on", qos=0, retain=True)
            elif host.lower() == "openmediavault" or host.lower() == "omv":
                #print(psutil.sensors_temperatures())
                #print(psutil.sensors_fans())
                sences = psutil.sensors_temperatures()
                #print(sences)
                cpu_data = sences["coretemp"][0]
                mb_data = sences["acpitz"][0]
                mem_data = psutil.virtual_memory()
                swap_data = psutil.swap_memory()
                #cpu_usage = psutil.cpu_percent(interval=1)
                load1, load5, load15 = psutil.getloadavg()
                cpu_usage = round((load1/os.cpu_count()) * 100, 1)
                print(psutil.getloadavg())
                print("CPU Util : {}".format(cpu_usage))
                print(mem_data)
                print(mem_data.percent)
                raid_data = psutil.disk_usage('/srv/dev-disk-by-uuid-02fbe97a-cd9a-4511-8bd5-21f8516353ee')
                #print(psutil.virtual_memory())
                #print(dict(psutil.virtual_memory()._asdict()))
                #cmnd = "sensors -j|grep -v \"Can't read\""
                #status, output = subprocess.getstatusoutput(cmnd)
                #print(output)
                #print(type(output))
                #jn1 = json.loads(output)
                stat_rsync = subprocess.call(["systemctl", "is-active", "--quiet", "rsync"])
                if(stat_rsync == 0):  # if 0 (active), print "Active"
                    stat_rsync = "on"
                else:
                    stat_rsync = "off"
                #sdiskusage = psutil.disk_partitions()
                disk_usage = raid_data[3]
                print(disk_usage)
                sys_uptime = str(datetime.timedelta(seconds=round(time.time() - psutil.boot_time(), 0)))
                reboot_pending = False
                if os.path.exists("/var/run/reboot-required"):
                    reboot_pending = True
                #str(datetime.timedelta(seconds=666))
                #print(str(jn1["coretemp-isa-0000"]["Package id 0"]["temp1_input"]))
                #print(str(jn1["asus-isa-0000"]["cpu_fan"]["fan1_input"]))
                #client.publish("sectorq/monitor/" + host.lower(), payload="{\"mb_temp\":0,\"mem_usage\":0,\"cpu_temp\":0,\"cpu_usage\":0,\"gpu_temp\":0,\"gpu_usage\":0}", qos=0, retain=False)
                client.publish("home-assistant/" + host + "/hwstats", payload='{"version":"' + VERSION + '","reboot":"' + str(reboot_pending) + '", "uptime":"' + str(sys_uptime) + '", "raid_usage": ' + str(disk_usage) + ',"rsync":"' + str(stat_rsync) +'", "MB_TEMP":' + str(mb_data.current) + ', "MEM_UTIL":' + str(mem_data.percent) + ', "CPU_TEMP":' + str(cpu_data.current) + ', "GPU_TEMP":0, "GPU_UTIL":0, "FAN_CPU":0, "VMEM_UTIL":' + str(swap_data.percent) + ', "CPU_UTIL":' + str(cpu_usage) + '}', qos=0, retain=False)
            elif host.lower() == "router":
                check_router()
            elif host.lower() == "nas":
                print("Getting VM info")
                
                cmnd = "/share/ZFS532_DATA/.qpkg/QKVM/usr/bin/virsh list --all"
                writeLog(cmnd)
                status, output = subprocess.getstatusoutput(cmnd)
                l = 1 
                lines = output.splitlines()
                VMS = {}
                for i in lines:
                    l = l + 1
                    if l < 4:
                        continue
                    line = re.split(r" {2,}", i)
                    print(str(line[0].strip()) + " " + str(line[1].strip()) + " " + str(line[2].strip()))
                    VMS[str(line[1].strip())] = str(line[2].strip())
                    
                    
                
                for m in VMS:
                
                    cmnd = "/share/ZFS532_DATA/.qpkg/QKVM/usr/bin/virsh  domstate " + m
                    #out = subprocess.Popen(cmnd.split())
                    writeLog(cmnd)
                    status, output = subprocess.getstatusoutput(cmnd)
                    writeLog(output)
                    if output.strip() ==  "running":
                        client.publish("sectorq/systems/nas/" + m, payload=1, qos=0, retain=True)
                    else:
                        client.publish("sectorq/systems/nas/" + m, payload=0, qos=0, retain=True)        
            
        
        if FILE_TIMESTAMP != mtime:
            writeLog("Script updated ! restarting...")
            #os.execv(sys.executable, ['python'] + sys.argv)
            #os.system("/share/ZFS530_DATA/.qpkg/QPython39/bin/python3 mqtt_srv.py")
            
            if host.lower() == "nas":
                sys.stdout.flush()
                os.execv("/share/ZFS530_DATA/.qpkg/QPython39/bin/python3", sys.argv)    
            if host.lower() == "router" or host.lower() == "omv":
                #sys.stdout.flush()
                #os.execv(sys.argv, "")
                print("argv was",sys.argv)
                print("sys.executable was", sys.executable)
                print("restart now")

                os.execv(sys.executable, ['python3'] + sys.argv)
                #os.startfile(sys.argv[0])
                sys.exit()