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

set "user="

for /f "skip=1 tokens=1,* delims=\" %%A in ('
    wmic computersystem get username ^|
    powershell -noprofile -command "$input.trim()"
') do set "user=%%~B"

for %%p in ("C:\Users\%user%\desktop\*") do (
	If /I "%%~xp"==".jpg" (move /y "%%p" "C:\Users\%user%\Pictures\%%~nxp")
	If /I "%%~xp"==".jpeg" (move /y "%%p" "C:\Users\%user%\Pictures\%%~nxp")
	If /I "%%~xp"==".png" (move /y "%%p" "C:\Users\%user%\Pictures\%%~nxp")
	If /I "%%~xp"==".gif" (move /y "%%p" "C:\Users\%user%\Pictures\%%~nxp")
)
"""

# Schedule the batch script to run at login
task_name = 'Comodo-MoveImagesAtLogin'
batch_script_path = os.path.join(os.environ["PROGRAMDATA"], "move_images.bat")

with open(batch_script_path, "w") as f:
    f.write(BatchScript)

with DisableFileSystemRedirection():
    task_cmd = 'schtasks /ru "SYSTEM" /create /sc ONLOGON /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.")
