import sys
from subprocess import Popen, PIPE
 
def alert(arg):
    sys.stderr.write("%d%d%d" % (arg, arg, arg))

def ecmd(command):   
    obj = Popen(command, shell = True, stdout = PIPE, stderr = PIPE)
    out, err = obj.communicate()
    ret=obj.returncode
    return (ret, out, err)
 
def is_firewall_enabled():
    try:
        # Define the command as a list of strings
        command = ['powershell', '-Command', 'Get-NetFirewallProfile | Select-Object Name, Enabled']

        # Get the returncode, output and error
        returncode, output, error = ecmd(command)

        if returncode==0:
            # Decode the output from bytes to a UTF-8 string
            output = output.decode('utf-8')
    
            # Check if all three firewall profiles are enabled
            if all("True" in line.split()[1] for line in output.splitlines() if line.startswith("Domain") or line.startswith("Private") or line.startswith("Public")):
                return 0
            else:
                return 1
        else:
            if error:
                print("Error occurred while checking firewall status: \n%s"%(error))
            else:
                print("something went wrong while checking firewall status. Return code: %s"%(returncode))
            return 2
    except Exception as e:
        print("Error occurred while checking firewall status: {}".format(e))
        return 2

def Enable_Firewall_for_all():
    returncode, output, error = ecmd(['powershell', 'Set-NetFirewallProfile -Profile Domain, Public, Private -Enabled True'])

    if returncode==0:
        print("successfully enabled all the Firewall profiles")
        if output:
            print(output)
    else:
        if error:
            print("Error occurred while turning on firewall profiles: \n%s"%(error))
        else:
            print("something went wrong while turning on firewall profiles. Return code: %s"%(returncode))
    

 
# Main script logic
try:
    # Check the firewall status
    check = is_firewall_enabled()
    if check==0:
        print("Firewall is turned ON for all profiles.")
        alert(0)  # Turn off the alert
    elif check == 1:
        print("ALERT: Firewall is turned OFF for one or more profiles!")
        print("Turning ON Firewall profiles")
        Enable_Firewall_for_all()
        alert(1)  # Turn on the alert
    elif check == 2:
        alert(1) # Turn off the alert
except Exception as e:
    print("Error occurred: {}".format(e))
    alert(1)  # Ensure an alert is raised if there is an error