#!/usr/bin/python
import subprocess
import getopt
import sys
import time
import requests
import re
__IP = '192.168.77.106'

try:
    opts, args = getopt.getopt(sys.argv[1:], "d:p:", ["destination=", "publish", "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 in ("-d", "--destination"):
        __IP = a
    elif o in ("-p", "--publish"):
        _PUBLISH = True
    else:
        _WIZZARD = True
        
        
__RULES = ["EMAIL993", "EMAIL25", "EMAIL143", "EMAIL995", "EMAIL465", "HTTPS", "HTTP"]

for i in __RULES:
    print(i)
    status, output = subprocess.getstatusoutput("uci set firewall." + i + ".dest_ip='" + __IP + "'")
status, output = subprocess.getstatusoutput("uci commit")
       
    
for i in __RULES:    
    status, output = subprocess.getstatusoutput("uci get firewall." + i + ".dest_ip")
    #print(output)
time.sleep(3)
status, output = subprocess.getstatusoutput("/etc/init.d/firewall restart")

if __IP == "192.168.77.246":
    act = "start"
    print("Starting containers on  Raspbian!")
else:
    act = "stop"
    print("Stopping containers on  Raspbian!")

status, output = subprocess.getstatusoutput("docker -H ssh://root@192.168.77.246  " + act + " mosquitto_mosquitto_1 HomeAssistant mailu_resolver_1 mailu_redis_1 mailu_smtp_1 mailu_imap_1 mailu_antispam_1 mailu_webmail_1 mailu_admin_1 mailu_front_1 nextcloud_db_1 nextcloud_app_1 webhub_client_1 nginx-proxy-manager_db_1 nginx-proxy-manager_app_1 ")

MQTT_BROKER = __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:
    if not re.match('([0-9]{1,3}).([0-9]{1,3}).([0-9]{1,3}).([0-9]{1,3})', sys_ip):
        print("wrong ip : " + str(sys_ip))
        continue
    print("This 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
