#!/usr/bin/env python
# -*- coding: utf-8 -*-


# ----------------------------
# Configuration / Variables
# ----------------------------
Drive = 'D:'                         # Drive to encrypt
email_to = ['admin@example.com']     # List of recipients
email_from = 'your.email@gmail.com'  # Sender email
email_password = 'your-app-password' # App Password which we configured
smtp_server = 'smtp.gmail.com'       # SMTP server
smtp_port = 587                      # SMTP port (TLS - 587, SSL - 465)
recovery_save_path = r'C:\RecoveryKeys'  # Folder to save recovery key
email_subject_prefix = 'BitLocker Alert'

# ----------------------------
# Imports
# ----------------------------
import os, re, subprocess, socket, ctypes, smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# ----------------------------
# Helper Functions
# ----------------------------
def computername():
    return os.environ.get('COMPUTERNAME', 'UnknownHost')

def ipaddress():
    try:
        return socket.gethostbyname(socket.gethostname())
    except:
        return "UnknownIP"

class disable_fsredir:
    """Disable File System Redirection for 64-bit Windows"""
    _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, a,b,c):
        if self.success:
            self._revert(self.old_value)

def run_cmd(cmd):
    """Run a command and return UTF-8 decoded output"""
    with disable_fsredir():
        output = os.popen(cmd).read()
        return output.decode('utf-8', 'ignore')

def send_email(subject, body):
    """Send email securely using SMTP"""
    try:
        msg = MIMEMultipart()
        msg["From"] = email_from
        msg["To"] = ",".join(email_to)
        msg["Subject"] = subject
        msg.attach(MIMEText(body.encode('utf-8'), 'plain', 'utf-8'))

        try:
            server = smtplib.SMTP(smtp_server, smtp_port)
            server.starttls()
        except:
            server = smtplib.SMTP_SSL(smtp_server, smtp_port)

        server.login(email_from, email_password)  # password never printed
        server.sendmail(email_from, email_to, msg.as_string())
        server.quit()
        return "Email sent successfully."
    except Exception as e:
        return "Email failed: %s" % str(e)

# ----------------------------
# Main Logic
# ----------------------------
subject = "%s - %s - Drive: %s" % (email_subject_prefix, computername(), Drive)
msgbody = "BitLocker Status Report\n"
msgbody += "Hostname: %s\nIP: %s\nDrive: %s\n\n" % (computername(), ipaddress(), Drive)

# Check current BitLocker status
status_output = run_cmd("manage-bde -status %s" % Drive)
protection = re.findall(r"Protection Status:\s*(.*)", status_output)
conversion = re.findall(r"Conversion Status:\s*(.*)", status_output)

status = " ".join(protection)
convert = " ".join(conversion)

msgbody += "Protection Status: %s\n" % status
msgbody += "Conversion Status: %s\n\n" % convert

if "On" in status or "Active" in convert or "Encrypting" in convert:
    msgbody += "BitLocker is already ON or encrypting. No action required.\n"
else:
    msgbody += "BitLocker is OFF — enabling encryption now...\n\n"
    enable_cmd = 'manage-bde -on %s -RecoveryKey %s -RecoveryPassword' % (Drive, recovery_save_path)
    enable_output = run_cmd('powershell "%s"' % enable_cmd)
    msgbody += "Command Output:\n%s\n" % enable_output

# Detect recovery key files
try:
    keyfiles = [f for f in os.listdir(recovery_save_path) if f.endswith('.BEK') or f.endswith('.txt')]
    if keyfiles:
        msgbody += "\nRecovery Key Files Stored:\n"
        for kf in keyfiles:
            msgbody += "- %s\\%s\n" % (recovery_save_path, kf)
    else:
        msgbody += "\n No recovery key file detected.\n"
except:
    msgbody += "\n Could not access recovery key folder: %s\n" % recovery_save_path

# Output status
print(msgbody)
print(send_email(subject, msgbody))
exit(0)
