#To define a particular parameter, replace the 'parameterName' inside itsm.getParameter('parameterName') with that parameter's name
import ctypes
import os
import smtplib
import subprocess
import socket
from datetime import datetime
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

Receiver = itsm.getParameter('EmailTo')  ## Provide an 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.
text = "Top 10 disk consuming files details are given in this attachment"

def gmail(sender_email,password,receiver, text, FilePath):
    try:
        msg = MIMEMultipart()
        msg["From"] = sender_email
        msg["To"] = receiver
        msg["Subject"] = "Top 10 disk consuming files"
        msg.attach(MIMEText(text, 'plain'))
        attachment = open(FilePath, "rb")
        p = MIMEBase('application', 'octet-stream')
        p.set_payload((attachment).read())
        # encode into base64
        p.add_header('Content-Disposition', "attachment; filename= %s" % os.path.basename(FilePath))
        encoders.encode_base64(p)
        # attach the instance 'p' to instance 'msg'
        msg.attach(p)
        server = smtplib.SMTP("smtp.gmail.com",587)
        server.starttls()
        server.login(sender_email,password)
        server.sendmail(sender_email, receiver, msg.as_string())
        server.quit()
        return "Top 10 disk consuming files details has been mailed successfully"
    except Exception as e:
        return e


DateTime = datetime.now()
sysName = socket.gethostname()

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)


FilePath = os.environ['USERPROFILE'] + r'\Execution_Report.txt'

size_cmd = "get-ChildItem C:\ -recurse -erroraction silentlycontinue | sort length -descending | select -first 10 " \
           "name, @{Name='Size(GB)';Expression={($_.Length / 1073741824).ToString('N2')}}"

Directory_cmd = "get-ChildItem C:\ -recurse -erroraction silentlycontinue | sort length -descending | select -first " \
                "10 directory"

AllCMD = [size_cmd, Directory_cmd]
ExOut = []


def ExecuteCmd(cmd):
    with disable_file_system_redirection():
        obj = subprocess.Popen(["powershell", cmd], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                               universal_newlines=True)
        out, err = obj.communicate()
        return out


for cmd in AllCMD:
    ExOut.append(ExecuteCmd(cmd))

SizeCnt = ExOut[0].split("\n")[1:]
dirCnt = ExOut[1].split("\n")[1:]

content = sysName + "\t\t" + DateTime.strftime("LAST STATUS UPDATE: %m/%d/%y %H:%M:%S %p") + "\n"
try:
    if ExOut[0] != "" and ExOut[1] != "":
        if len(SizeCnt) > 12 and len(dirCnt) > 12:
            for Rng in range(12):
                content = content + SizeCnt[Rng] + "  " + dirCnt[Rng] + "\n"

            FilePath = os.environ['USERPROFILE'] + "\\" + sysName + "_" + "ExecutionReport.txt"
            print content
            with open(FilePath, 'w') as w:
                w.write(content + "\n")
            print gmail(Sender, Password, Receiver, text, FilePath)
            if os.path.exists(FilePath):
                os.remove(FilePath)
    else:
        print "Script execution failed"
except Exception as e:
    print e