Fast_Start_up = "off" #if you want to turn on Fast_Start_up, Give "on"; else, give "off"

Sleep =  "off" #if you want to turn on Sleep, Give "on"; else, give "off"

Hibernate = "off" #if you want to turn on Hibernate, Give "on"; else, give "off"

Power_Plan = "High Performance"
"""
you can give following power plans in the Power_Plan variable:
    1)High Performance
    2)Balanced
    3)Power saver
Make Sure that you give these names exactly like shown above without any spelling mistake and extra space.
"""

set_never_go_to_sleep_when_plugged_in = "no"
"""
give "yes" if you want to Change the power setting to never go to sleep when plugged in; else, give "no"
"""

When_I_Press_the_Power_button = "Shut down"
"""
you can give following options in the When_I_Press_the_Power_button variable:
    1)Shut down
    2)Sleep
    3)Hibernate
    4)Do nothing
    5)Turn off the display
Make Sure that you give these names exactly like shown above without any spelling mistake and extra space.
"""

When_I_Press_the_Sleep_button = "Sleep"
"""
you can give following options in the When_I_Press_the_Sleep_button variable:
    1)Sleep
    2)Hibernate
    3)Do nothing
    4)Turn off the display
Make Sure that you give these names exactly like shown above without any spelling mistake and extra space.
"""

import os
from subprocess import PIPE, Popen
import ctypes
import re
import ssl
import urllib2

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 ecmd(command):   
    from subprocess import Popen, PIPE
    import ctypes
    
    with disable_file_system_redirection():
        obj = Popen(command, shell = True, stdout = PIPE, stderr = PIPE)
    out, err = obj.communicate()
    ret=obj.returncode
    if ret==0:
        if out:
            return out.strip()
        else:
            return ret
    else:
        if err:
            return err.strip()
        else:
            return ret

def downloadFile(DownTo, fromURL):
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'}
    context = ssl._create_unverified_context()
    request = urllib2.Request(fromURL, headers=headers)
    req = urllib2.urlopen(request,context=context)
    try:
        with open(DownTo, 'wb') as f:
            while True:
                chunk = req.read(100*1000*1000)
                if chunk:
                    f.write(chunk)
                else:
                    break
        if os.path.isfile(DownTo):
            return '{} - {}KB'.format(DownTo, os.path.getsize(DownTo)/1024)
		
    except:
        return 'Please Check URL or Download Path!'

def import_and_activate_powerplan(url,fileName, guid):
    Down_path=os.environ['TEMP']
    DownTo = os.path.join(Down_path, fileName)
    print(downloadFile(DownTo, url))
    print("importing the missing powerplan - %s"%(fileName))
    print(ecmd('powercfg -import "%s" %s'%(DownTo,guid)))
    print(ecmd('powercfg /SETACTIVE "%s"'%(guid)))

def HighPerformance():
    with disable_file_system_redirection():
        power_plans_guid = os.popen("powercfg /list").read()
    
        if not "High performance" in power_plans_guid:
            print(ecmd('powercfg -duplicatescheme 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c'))
            power_plans_guid = os.popen("powercfg /list").read()
            if "High performance" in power_plans_guid:
                HP_GUID = re.findall("Power Scheme GUID:(.*)[(]High performance[)].*", power_plans_guid)[0].strip()
                print(ecmd('powercfg /SETACTIVE "%s"'%(HP_GUID)))
            else:
                url = "https://script-downloads.itarian.com/power%20plans/High%20performance.pow"
                import_and_activate_powerplan(url,"High performance.pow", "8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c")
        else:
            HP_GUID = re.findall("Power Scheme GUID:(.*)[(]High performance[)].*", power_plans_guid)[0].strip()
            print(ecmd('powercfg /SETACTIVE "%s"'%(HP_GUID)))

def Balanced():
    with disable_file_system_redirection():
        power_plans_guid = os.popen("powercfg /list").read()

        if not "Balanced" in power_plans_guid:
            print(ecmd('powercfg -duplicatescheme 381b4222-f694-41f0-9685-ff5bb260df2e'))
            power_plans_guid = os.popen("powercfg /list").read()
            if "Balanced" in power_plans_guid:
                B_GUID = re.findall("Power Scheme GUID:(.*)[(]Balanced[)].*", power_plans_guid)[0].strip()
                print(ecmd('powercfg /SETACTIVE "%s"'%(B_GUID)))
            else:
                url = "https://script-downloads.itarian.com/power%20plans/Balanced.pow"
                import_and_activate_powerplan(url,"Balanced.pow", "381b4222-f694-41f0-9685-ff5bb260df2e")
        else:
            B_GUID = re.findall("Power Scheme GUID:(.*)[(]Balanced[)].*", power_plans_guid)[0].strip()
            print(ecmd('powercfg /SETACTIVE "%s"'%(B_GUID)))

def PowerSaver():
    with disable_file_system_redirection():
        power_plans_guid = os.popen("powercfg /list").read()

        if not "Power saver" in power_plans_guid:
            print(ecmd('powercfg -duplicatescheme a1841308-3541-4fab-bc81-f71556f20b4a'))
            power_plans_guid = os.popen("powercfg /list").read()
            if "Power saver" in power_plans_guid:
                PS_GUID = B_GUID = re.findall("Power Scheme GUID:(.*)[(]Power saver[)].*", power_plans_guid)[0].strip()
                print(ecmd('powercfg /SETACTIVE "%s"'%(PS_GUID)))
            else:
                url = "https://script-downloads.itarian.com/power%20plans/Power%20saver.pow"
                import_and_activate_powerplan(url,"Power saver.pow", "40a2b0b8-9231-4fda-a3db-5c3de1e45d71")
        else:
            PS_GUID = B_GUID = re.findall("Power Scheme GUID:(.*)[(]Power saver[)].*", power_plans_guid)[0].strip()
            print(ecmd('powercfg /SETACTIVE "%s"'%(PS_GUID)))


BAT='''
powercfg.exe -x -monitor-timeout-ac 0
powercfg.exe -x -monitor-timeout-dc 0
powercfg.exe -x -disk-timeout-ac 0
powercfg.exe -x -disk-timeout-dc 0
powercfg.exe -x -standby-timeout-ac 0
powercfg.exe -x -standby-timeout-dc 0
powercfg.exe -x -hibernate-timeout-ac 0
powercfg.exe -x -hibernate-timeout-dc 0

'''

if Fast_Start_up.strip().lower()=="off":
    print(ecmd('reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Power" /v HiberbootEnabled /t REG_DWORD /d 0 /f'))
elif Fast_Start_up.strip().lower()=="on":
    print(ecmd('reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Power" /v HiberbootEnabled /t REG_DWORD /d 1 /f'))
else:
    print("Error: please check the spelling in the Fast_Start_up variable")   
   
if Sleep.strip().lower()=="off":
    print(ecmd('reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FlyoutMenuSettings" /v ShowSleepOption /t REG_DWORD /d 0 /f'))
elif Sleep.strip().lower()=="on":
    print(ecmd('reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FlyoutMenuSettings" /v ShowSleepOption /t REG_DWORD /d 1 /f'))
else:
    print("Error: please check the spelling in the Sleep variable")

if Hibernate.strip().lower()=="off":
    print(ecmd('reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FlyoutMenuSettings" /v ShowHibernateOption /t REG_DWORD /d 0 /f'))
elif Hibernate.strip().lower()=="on":
    print(ecmd('reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FlyoutMenuSettings" /v ShowHibernateOption /t REG_DWORD /d 1 /f'))
else:
    print("Error: please check the spelling in the Hibernate variable")
    
Balanced()
if When_I_Press_the_Power_button.strip().lower()=="do nothing":
    print(ecmd(r'powercfg -setdcvalueindex SCHEME_CURRENT 4f971e89-eebd-4455-a8de-9e59040e7347 7648efa3-dd9c-4e3e-b566-50f929386280 0'))
    print(ecmd(r'powercfg -setacvalueindex SCHEME_CURRENT 4f971e89-eebd-4455-a8de-9e59040e7347 7648efa3-dd9c-4e3e-b566-50f929386280 0'))
elif When_I_Press_the_Power_button.strip().lower()=="sleep":
    print(ecmd(r'powercfg -setdcvalueindex SCHEME_CURRENT 4f971e89-eebd-4455-a8de-9e59040e7347 7648efa3-dd9c-4e3e-b566-50f929386280 1'))
    print(ecmd(r'powercfg -setacvalueindex SCHEME_CURRENT 4f971e89-eebd-4455-a8de-9e59040e7347 7648efa3-dd9c-4e3e-b566-50f929386280 1'))
elif When_I_Press_the_Power_button.strip().lower()=="hibernate":
    print(ecmd(r'powercfg -setdcvalueindex SCHEME_CURRENT 4f971e89-eebd-4455-a8de-9e59040e7347 7648efa3-dd9c-4e3e-b566-50f929386280 2'))
    print(ecmd(r'powercfg -setacvalueindex SCHEME_CURRENT 4f971e89-eebd-4455-a8de-9e59040e7347 7648efa3-dd9c-4e3e-b566-50f929386280 2'))
elif When_I_Press_the_Power_button.strip().lower()=="shut down":
    print(ecmd(r'powercfg -setdcvalueindex SCHEME_CURRENT 4f971e89-eebd-4455-a8de-9e59040e7347 7648efa3-dd9c-4e3e-b566-50f929386280 3'))
    print(ecmd(r'powercfg -setacvalueindex SCHEME_CURRENT 4f971e89-eebd-4455-a8de-9e59040e7347 7648efa3-dd9c-4e3e-b566-50f929386280 3'))
elif When_I_Press_the_Power_button.strip().lower()=="turn off the display":
    print(ecmd(r'powercfg -setdcvalueindex SCHEME_CURRENT 4f971e89-eebd-4455-a8de-9e59040e7347 7648efa3-dd9c-4e3e-b566-50f929386280 4'))
    print(ecmd(r'powercfg -setacvalueindex SCHEME_CURRENT 4f971e89-eebd-4455-a8de-9e59040e7347 7648efa3-dd9c-4e3e-b566-50f929386280 4'))
else:
    print("please check the spelling in the When_I_Press_the_Power_button variable")

if When_I_Press_the_Sleep_button.strip().lower()=="do nothing":
    print(ecmd(r'powercfg -setdcvalueindex SCHEME_CURRENT 4f971e89-eebd-4455-a8de-9e59040e7347 96996bc0-ad50-47ec-923b-6f41874dd9eb 0'))
    print(ecmd(r'powercfg -setacvalueindex SCHEME_CURRENT 4f971e89-eebd-4455-a8de-9e59040e7347 96996bc0-ad50-47ec-923b-6f41874dd9eb 0'))
elif When_I_Press_the_Sleep_button.strip().lower()=="sleep":
    print(ecmd(r'powercfg -setdcvalueindex SCHEME_CURRENT 4f971e89-eebd-4455-a8de-9e59040e7347 96996bc0-ad50-47ec-923b-6f41874dd9eb 1'))
    print(ecmd(r'powercfg -setacvalueindex SCHEME_CURRENT 4f971e89-eebd-4455-a8de-9e59040e7347 96996bc0-ad50-47ec-923b-6f41874dd9eb 1'))
elif When_I_Press_the_Sleep_button.strip().lower()=="hibernate":
    print(ecmd(r'powercfg -setdcvalueindex SCHEME_CURRENT 4f971e89-eebd-4455-a8de-9e59040e7347 96996bc0-ad50-47ec-923b-6f41874dd9eb 2'))
    print(ecmd(r'powercfg -setacvalueindex SCHEME_CURRENT 4f971e89-eebd-4455-a8de-9e59040e7347 96996bc0-ad50-47ec-923b-6f41874dd9eb 2'))
elif When_I_Press_the_Sleep_button.strip().lower()=="turn off the display":
    print(ecmd(r'powercfg -setdcvalueindex SCHEME_CURRENT 4f971e89-eebd-4455-a8de-9e59040e7347 96996bc0-ad50-47ec-923b-6f41874dd9eb 4'))
    print(ecmd(r'powercfg -setacvalueindex SCHEME_CURRENT 4f971e89-eebd-4455-a8de-9e59040e7347 96996bc0-ad50-47ec-923b-6f41874dd9eb 4'))

if Power_Plan.strip().lower()=="high performance":
    HighPerformance()       
elif Power_Plan.strip().lower()=="balanced":
    Balanced()     
elif Power_Plan.strip().lower()=="power saver":
    PowerSaver()
else:
    print("Error: please check the spelling in the power plan variable")
        

if set_never_go_to_sleep_when_plugged_in.lower()=="yes":
    path=os.environ['Programdata']+"\power.bat"
    with open(path,"w") as f:
        f.write(BAT)
    print(ecmd(path))
    os.remove(path)
    
