import ctypes
import re
import socket
import subprocess
from datetime import datetime
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
import os
import sys

Receiver = itsm.getParameter('EmailTo')  # Provide a Toemail address where the mail need to be sent. the datatype should be a string.
Sender = itsm.getParameter('EmailFrom')  # Provide the From Email address from which the mail to be send. the datatype should be a string.
Password = itsm.getParameter('Password')  # Provide app password for from email. the datatype should be a string.
MailFlag = itsm.getParameter('MailFlag')  # Provide mail flag 1 or 0 (1 - outlook, 0 - gmail). the datatype should be a int.


def gmail(sender_email, password, receiver, text):
    try:
        msg = MIMEMultipart()
        msg["From"] = sender_email
        msg["To"] = receiver
        msg["Subject"] = "Bitlocker Status"
        msg.attach(MIMEText(text, 'plain'))
        if MailFlag:
            server = smtplib.SMTP("smtp.office365.com", 587)
        else:
            server = smtplib.SMTP("smtp.gmail.com", 587)
        server.starttls()
        server.login(sender_email, password)
        server.sendmail(sender_email, receiver, msg.as_string())
        server.quit()
        print "\nBitlocker Status has been mailed successfully"
    except Exception as e:
        print e


# This script is used to Check the Bit Locker Drive Encryption and Decryption status
# Please Enter the Drive you want to check the  Bitlocker Encryption status

Drive = 'C'
ps_command = r'manage-bde -status ' + Drive + ':'
print ps_command


def alert(arg):
    sys.stderr.write("%d%d%d" % (arg, arg, arg))


# Please use "alert(1)" to turn on the monitor(trigger an alert)
# Please use "alert(0)" to turn off the monitor(disable an alert)
# Please do not change above block and write your script below


def checkdrive():
    class disable_file_system_redirection:
        _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
        _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection

        def __enter__(self):
            self.old_value = ctypes.c_long()
            self.success = self._disable(ctypes.byref(self.old_value))

        def __exit__(self, type, value, traceback):
            if self.success:
                self._revert(self.old_value)

    with disable_file_system_redirection():
        process = subprocess.Popen('powershell "%s"' % ps_command, shell=True, stdout=subprocess.PIPE)
    result = process.communicate()
    ret = process.returncode

    if ret == 0:
        if result[0]:
            m = result[0].strip()
            n = re.findall('Conversion\sStatus:\s\s\s\s(.*)', m)
            percent = re.findall('Percentage\sEncrypted:\s(.*)', m)
            percent = percent[0].strip()
            out = n[0].strip()
            if "Fully Decrypted" in out:
                print "Bitlocker is not enabled for " + Drive + " Drive"
                alert(1)
                content = socket.gethostname() + "\t\t" + datetime.now().strftime(
                    "LAST STATUS UPDATE: %m/%d/%y %H:%M:%S %p") + "\n\n" + "Bitlocker is not enabled for " + Drive + " Drive"
                gmail(Sender, Password, Receiver, content)
            else:
                if "Used Space Only Encrypted" in out:
                    print "The used space is Encrypted fully"
                    print percent
                    alert(0)
                elif "Fully Encrypted" in out:
                    print "The" + Drive + " Drive is fully encrypted"
                    print percent
                    alert(0)
                elif "Encryption in Progress" in out:
                    print "The " + Drive + " Drive  Encryption is in progress"
                    print percent
                    alert(0)
                elif "Decryption in Progress" in out:
                    print Drive + "Decryption is in progress"
                    print percent
                    alert(0)
                elif "Unknown" in out:
                    print Drive + " is locked"
                    alert(0)
        else:
            print None

    else:
        print '%s\n%s' % (str(ret), str(result[1]))


checkDrive = os.popen('wmic logicaldisk get description,name|findstr "Local Fixed Disk"').read()
if Drive in checkDrive:
    checkdrive()
else:
    print "Entered drive " + Drive + " does not occurs in the system."
    alert(1)
