# To define a particular parameter, replace the 'parameterName' inside itsm.getParameter('parameterName') with that parameter's name
import ctypes
import os
import subprocess


CheckPoint = itsm.getParameter('CheckPoint')


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)


def ExecuteCmd(cmd):
    with disable_file_system_redirection():
        obj = subprocess.Popen(["powershell", cmd], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, err = obj.communicate()
        ret = obj.returncode
        return out, err, ret


def CreateScriptFile(ps_content):
    try:
        file_name = 'ScriptFile.ps1'
        file_path = os.path.join(os.environ['TEMP'], file_name)
        with open(file_path, 'wb') as wr:
            wr.write(ps_content)
            wr.close()
        return file_path
    except:
        return ''


ExecuteCmd('Set-ExecutionPolicy RemoteSigned -Force')
out = ExecuteCmd('(Get-VM).Name')[0].strip()
if out != '':
    VMS = out.split('\r\n')
    PsCmd = r''
    for vm in range(len(VMS)):
        PsCmd = PsCmd + ' Checkpoint-VM -Name "' + VMS[vm] + '" -SnapshotName ' + CheckPoint + str(vm + 1) + '\n'
    PSFile = CreateScriptFile(PsCmd)
    if os.path.exists(PSFile):
        res = ExecuteCmd(PSFile)
        if not res[2]:
            print "checkpoint for all VM has been Created"
        else:
            print res[1]
        os.remove(PSFile)
    else:
        print ("Script file does not exists")
else:
    print "Virtual machine Not available"
