days=9    ## change the number of days, you would like to check for uptime.
t='00:05:00'  ## provide the time of delay for the restart, make sure that time is given in this format(HH:MM:SS).

import os
import ctypes
import time

def get_sec(time_str):
    h, m, s = time_str.split(':')
    return int(h) * 3600 + int(m) * 60 + int(s)
time1=get_sec(t)
input='''
$os = Get-WmiObject win32_operatingsystem
$uptime = (Get-Date) - ($os.ConvertToDateTime($os.lastbootuptime))
$Display = "Windows-Endpoint Uptime in Days: " + $Uptime.days 
Write-Output $Display 
if($uptime.days -ge %s)
{
Write-Output "Time to restart the Windows-Endpoint and the Force Restart is Initiated!"
Write-Output "Restart"
}
Else
{
"No restart Required"
}
'''%(str(days))

VBScr = '''Dim WshShell, BtnCode
Set WshShell = WScript.CreateObject("WScript.Shell")
BtnCode = WshShell.Popup("System needs to reboot. Do you want to reboot now?", %s, "Administrator Required Reboot:", 4 + 32)
If BtnCode=6 Then
    strShutdown = "shutdown.exe -r -t 20 -f"
    Set objShell = CreateObject("WScript.Shell")
    objShell.Run strShutdown, 0, False
ElseIf BtnCode=7 Then
    WScript.Echo 1
Else
    WScript.Echo 2
End If'''%(time1 - 60)

VBScr_popup = '''Dim WshShell, BtnCode
Set WshShell = WScript.CreateObject("WScript.Shell")
BtnCode = WshShell.Popup("System will shutdown, Make sure to save any opened files", %s, "Administrator Required Reboot:", 4 + 32)
'''%(time1 - 60)

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():
    filep=os.path.join(os.environ['SYSTEMDRIVE'], os.sep, 'checkboottime.ps1')
    with open(filep, "w") as fobj:
        fobj.write(input)    
with disable_file_system_redirection():
    out=os.popen('powershell.exe -executionpolicy bypass -file %s'%(filep)).read()
print out
if "Restart" in out:

    with disable_file_system_redirection(): 
        FILEPATH = os.path.join(os.environ['TEMP'], 'vbscript.vbs')
        with open(FILEPATH, 'w') as f:
            f.write(VBScr)
			
        FILEPATH_popup = os.path.join(os.environ['TEMP'], 'vbscript_popup.vbs')
        with open(FILEPATH_popup, 'w') as f:
            f.write(VBScr_popup)
        
        def ExecuteCMD(CMD, OUT = False):
            import ctypes
            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)

            from subprocess import PIPE, Popen
            with disable_file_system_redirection():
                OBJ = Popen(CMD, shell = True, stdout = PIPE, stderr = PIPE)
            out, err = OBJ.communicate()
            RET = OBJ.returncode
            if RET == 0:
                if OUT == True:
                    if out != '':
                        return out.strip()
                    else:
                        return True
                else:
                    return True
            else:
                return False

        def SeOutput(Pat, Str):
            import re
            se = re.search(Pat, Str)
            if se:
                return int(se.group().strip())
            else:
                return False

        if os.path.isfile(FILEPATH):
            OUTPUT = ExecuteCMD('cscript "'+FILEPATH+'"', True)
            UserRes = SeOutput(r'[\r\n]+[0-9]', OUTPUT)
            if UserRes == 1:
                print "User did not allow the reboot"
                print os.popen("shutdown -r -t %s"%time1).read()
                OUTPUT = ExecuteCMD('cscript "'+FILEPATH_popup+'"', True)
            elif UserRes == 2:
                print "User did not response the alert"
                print os.popen("shutdown -r -t %s"%time1).read()
                OUTPUT = ExecuteCMD('cscript "'+FILEPATH_popup+'"', True)
            else:
                print 'Success: User allowed the reboot'
                print os.popen("shutdown -r").read()
        if os.path.exists(FILEPATH):
            os.remove(FILEPATH)
        if os.path.exists(FILEPATH_popup):
            os.remove(FILEPATH_popup)
if os.path.exists(filep):
    os.remove(filep)
