Predefined_IP = r"21.***.**.**" #give here the predefined Public IP address

import subprocess
import os
import ctypes

class DisableFileSystemRedirection:
    _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)

BatchScript = r"""
@echo off
Ping www.google.nl -n 1 -w 1000
IF %ERRORLEVEL% EQU 0 (
    GOTO disconnect
) ELSE (
    GOTO END
)

:disconnect
set PredefinedIP="""+Predefined_IP+r"""
FOR /F "tokens=*" %%g IN ('curl "http://myexternalip.com/raw"') do (SET PIP=%%g)
if %PIP%==%PredefinedIP% (GOTO END) else (ipconfig /release)

:END
"""


task_name = 'disconnect_ip_cycle'
batch_script_path = os.path.join(os.environ["PROGRAMDATA"], "disconnect.bat")

with open(batch_script_path, "w") as f:
    f.write(BatchScript)

with DisableFileSystemRedirection():
    task_cmd = 'schtasks /ru "SYSTEM" /create /sc minute /mo 2 /tn "{}" /tr "{}" /rl HIGHEST /f'.format(task_name, batch_script_path)
    process = subprocess.Popen(task_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = process.communicate()
    ret = process.returncode

if ret == 0:
    if stdout:
        print("Scheduled task creation output:", stdout.decode('utf-8').strip())
    else:
        print("Scheduled task created successfully.")
else:
    if stderr:
        print("Error creating scheduled task:", stderr.decode('utf-8').strip())
    else:
        print("An error occurred while creating the scheduled task.")
