@setlocal DisableDelayedExpansion
@echo off


if defined PROCESSOR_ARCHITEW6432 (
set "_cmdf=%~f0"
setlocal EnableDelayedExpansion
start %SystemRoot%\Sysnative\cmd.exe /c ""!_cmdf!" %*"
exit /b
)

::  Set Path variable, it helps if it is misconfigured in the system

set "SysPath=%SystemRoot%\System32"
set "Path=%SysPath%;%SystemRoot%;%SysPath%\Wbem;%SysPath%\WindowsPowerShell\v1.0\"

::========================================================================================================================================

set _args=
set _elev=
set reset=
set Silent=
set activate=
set "_arg1=%~1"
if not defined _arg1 goto :NoProgArgs
set "_args=%~1"
set "_arg2=%~2"
set "_arg3=%~3"
set "_arg4=%~4"
if defined _arg2 set "_args=%~1 %~2"
if defined _arg3 set "_args=%~1 %~2 %~3"
if defined _arg4 set "_args=%~1 %~2 %~3 %~4"
for %%A in (%_args%) do (
if /i "%%A"=="-el" set _elev=1
if /i "%%A"=="/res" set Unattended=1&set activate=&set reset=1
if /i "%%A"=="/act" set Unattended=1&set activate=1&set reset=
if /i "%%A"=="/s" set Silent=1& set Unattended=1)
:NoProgArgs
for /f "tokens=6 delims=[]. " %%G in ('ver') do set winbuild=%%G
set "_psc=powershell"
set "Red="white" "DarkRed""
set "Green="white" "DarkGreen""
set "Magenta="white" "darkmagenta""
set "Gray="white" "darkgray""
set "nul=1>nul 2>nul"
set "ELine=echo: &call :color "==== ERROR ====" %Red% &echo:"
set line=________________________________________________________________________________________

if defined Silent if not defined activate if not defined reset exit /b
if defined Silent call :Begin >nul 2>&1 & exit /b

:Begin

::========================================================================================================================================

for %%i in (powershell.exe) do if "%%~$path:i"=="" (
echo: &echo ==== ERROR ==== &echo:
echo Powershell is not installed in the system.
echo Aborting...
goto Done
)

::========================================================================================================================================

if %winbuild% LSS 7600 (
%ELine%
echo Unsupported OS version Detected.
echo Project is supported only for Windows 7/8/8.1/10 and their Server equivalent.
goto Done
)

::========================================================================================================================================

%nul% reg query HKU\S-1-5-19 && (
goto :_Passed
) || (
if defined _elev goto :_E_Admin
)

set "_batf=%~f0"
set "_vbsf=%temp%\admin.vbs"
set _PSarg="""%~f0""" -el
if defined _args set _PSarg="""%~f0""" -el """%_args%"""

setlocal EnableDelayedExpansion

(
echo Set strArg=WScript.Arguments.Named
echo Set strRdlproc = CreateObject^("WScript.Shell"^).Exec^("rundll32 kernel32,Sleep"^)
echo With GetObject^("winmgmts:\\.\root\CIMV2:Win32_Process.Handle='" ^& strRdlproc.ProcessId ^& "'"^)
echo With GetObject^("winmgmts:\\.\root\CIMV2:Win32_Process.Handle='" ^& .ParentProcessId ^& "'"^)
echo If InStr ^(.CommandLine, WScript.ScriptName^) ^<^> 0 Then
echo strLine = Mid^(.CommandLine, InStr^(.CommandLine , "/File:"^) + Len^(strArg^("File"^)^) + 8^)
echo End If
echo End With
echo .Terminate
echo End With
echo CreateObject^("Shell.Application"^).ShellExecute "cmd.exe", "/c " ^& chr^(34^) ^& chr^(34^) ^& strArg^("File"^) ^& chr^(34^) ^& strLine ^& chr^(34^), "", "runas", 1
)>"!_vbsf!"

(%nul% cscript //NoLogo "!_vbsf!" /File:"!_batf!" -el "!_args!") && (
del /f /q "!_vbsf!"
exit /b
) || (
del /f /q "!_vbsf!"
%nul% %_psc% "start cmd.exe -arg '/c \"!_PSarg:'=''!\"' -verb runas" && (
exit /b
) || (
goto :_E_Admin
)
)
exit /b

:_E_Admin
%ELine%
echo This script require administrator privileges.
echo To do so, right click on this script and select 'Run as administrator'.
goto Done

:_Passed

::========================================================================================================================================

::  Fix for the special characters limitation in path name
::  Written by @abbodi1406

set "_work=%~dp0"
if "%_work:~-1%"=="\" set "_work=%_work:~0,-1%"

set "_batf=%~f0"
set "_batp=%_batf:'=''%"

set "_temp=%temp%"
set "_appdata=%appdata%"
set "_username=%username%"

for /F "tokens=2*" %%a in ('reg query "HKCU\Software\DownloadManager" /v ExePath') do call set "IDMan=%%b"

setlocal EnableDelayedExpansion

::========================================================================================================================================

reg query "HKLM\Hardware\Description\System\CentralProcessor\0" /v "Identifier" | find /i "x86" 1>nul && set arch=x86|| set arch=x64

if not exist "!IDMan!" (
if %arch%==x64 set "IDMan=C:\Program Files (x86)\Internet Download Manager\IDMan.exe"
if %arch%==x86 set "IDMan=C:\Program Files\Internet Download Manager\IDMan.exe"
)

if "%arch%"=="x86" (
set "CLSID=HKCU\Software\Classes\CLSID"
set "HKLM=HKLM\Software\Internet Download Manager"
) else (
set "CLSID=HKCU\Software\Classes\Wow6432Node\CLSID"
set "HKLM=HKLM\SOFTWARE\Wow6432Node\Internet Download Manager"
)

set RegData=%SystemRoot%\Temp\RegData.txt

set "line_2=echo:&echo _____________________________________________________________&echo:"

::========================================================================================================================================

if defined Unattended (
if defined reset goto _reset
if defined activate goto _activate
)

:MainMenu

cls
title  IDM Activation v0.5 - Gamesetup.ir
mode con: cols=79 lines=30

echo:
echo:
echo:                           Activation IDM - gamesetup.ir
echo:
echo:           _________________________________________________________
echo:                                                                    
echo:                                                                    
echo:                 [1] Activate IDM                                   
echo:                                                                    
echo:                 [2] Reset IDM Activation / Trial                   
echo:                 _____________________________________________      
echo:                                                                    
echo:                 [3] Toggle Windows Firewall                                              
echo:                 _____________________________________________      
echo:                                                                    
echo:                 [6] Exit                                           
echo:                                                                    
echo:           _________________________________________________________
echo:         
choice /C:123456 /N /M ">             Enter Your Choice in the Keyboard [1,2,3,6] : "

if errorlevel 6 exit /b
if errorlevel 5 goto Homepage
if errorlevel 4 call :ReadMe&goto MainMenu
if errorlevel 3 goto _tog_Firewall
if errorlevel 2 goto _reset
if errorlevel 1 goto _activate

::========================================================================================================================================

:_tog_Firewall

cls
title  Toggle Windows Firewall
mode con: cols=79 lines=30
NetSh AdvFirewall Show AllProfiles State|Find /I "OFF" >nul && (
set _status=Disabled
) || (
set _status=Enabled
)

echo:
echo:
echo:
echo:
echo:              Disable temporarily only when the activation option    
echo:                              does not work.                        
echo:           _________________________________________________________
echo:                                                                    
echo:                     Windows Firewall Status : %_status% 
echo:                 _____________________________________________     
echo:                                                                    
echo:                 [1] Enable Windows Firewall                       
echo:                                                                    
echo:                 [2] Disable Windows Firewall             
echo:                                                                    
echo:                 [3] Go back                                     
echo:                                                                    
echo:           _________________________________________________________
echo:         
choice /C:123 /N /M ">                Enter Your Choice [1,2,3] : "

if errorlevel 3 goto MainMenu
if errorlevel 2 goto Off_Firewall
if errorlevel 1 goto On_Firewall

::========================================================================================================================================

:On_Firewall

cls
echo:
echo:
echo Applying the command,
echo NetSh AdvFirewall Set AllProfiles State On
echo:
NetSh AdvFirewall Set AllProfiles State On >nul

NetSh AdvFirewall Show AllProfiles State|Find /I "OFF" >nul && (
call :color "Failed to enable Windows Firewall." %Red%
) || (
call :color "Windows Firewall is enabled." %Green%
)
%line_2%
echo Press any key to return...
pause >nul
goto _tog_Firewall

::========================================================================================================================================

:Off_Firewall

cls
echo:
echo:
echo Applying the command,
echo NetSh AdvFirewall Set AllProfiles State Off
echo:
NetSh AdvFirewall Set AllProfiles State Off >nul

NetSh AdvFirewall Show AllProfiles State|Find /I "ON" >nul && (
call :color "Failed to disable Windows Firewall." %Gray%
) || (
call :color "Windows Firewall is disabled." %Magenta%
echo:
call :color "Don''t forget to enable Windows Firewall after the activation." %Red%
)
%line_2%
echo Press any key to return...
pause >nul
goto _tog_Firewall

::========================================================================================================================================

:ReadMe

set "_ReadMe=%SystemRoot%\Temp\ReadMe.txt"
if exist "%_ReadMe%" del /f /q "%_ReadMe%" %nul%
call :export txt "%_ReadMe%"
start notepad "%_ReadMe%"
timeout /t 2 %nul%
del /f /q %_ReadMe%"
exit /b


::  Extract the text from batch script without character and file encoding issue
::  Thanks to @abbodi1406

:export

%nul% %_psc% "$f=[io.file]::ReadAllText('!_batp!') -split \":%~1\:.*`r`n\"; [io.file]::WriteAllText('%~2',$f[1].Trim(),[System.Text.Encoding]::ASCII);"
exit/b

:txt:
_________________________________

   Activation:
_________________________________

 - This script applies registry lock method to activate Internet download manager (IDM).

 - IDM updates can be installed directly without having to activate again.





 - Troubleshooting steps:

   - If any other activator was used to activate IDM previously then make sure to properly
     uninstall it with that same activator (if there is an option), this is specially important
     if any registry / firewall block method was used.

   - Uninstall the IDM from control panel.

   - Make sure the latest original IDM setup is used for the installation,
     you can download it from https://www.internetdownloadmanager.com/download.html

   - Now install the IDM and use the activate option in this script and if failed then,

     - Disable windows firewall with the script option, this help in case of leftover entries of
       previously used activator (some file patch method also creates firewall entries).

     - Some security programs may block this script, this is false-positive, as long as you 
       downloaded the file from original post (mentioned below in this page), temporary suspend
       Antivirus realtime protection, or exclude the downloaded file/extracted folder from scanning.

     - If you are still facing any issues, please contact me (mentioned below in this page).

_________________________________

   Reset IDM Activation / Trial:
_________________________________

 - Internet download manager provides 30 days trial period, you can use this script to 
   reset this Activation / Trial period whenever you want.
 
 - This option also can be used to restore status if in case the IDM reports fake serial
   key and other similar errors.

_________________________________

   OS requirement:
_________________________________

 - Project is supported only for Windows 7/8/8.1/10 and their Server equivalent.

_________________________________

 - Advanced Info,
_________________________________
 
   - For activation in unattended mode, run the script with /act parameter.
   - For reset in unattended mode, run the script with /res parameter.
   - To enable silent mode with above two methods, run the script with /s parameter.

Possible accepted values,

"IAS_xxxxxxxx.cmd" /act
"IAS_xxxxxxxx.cmd" /res
"IAS_xxxxxxxx.cmd" /act /s
"IAS_xxxxxxxx.cmd" /res /s

____________________________________________________________________________________________________

   Credits:
____________________________________________________________________________________________________

   @Dukun Cabul        - Original researcher of this IDM trial reset and activation logic,
                         made an Autoit tool for these methods, IDM-AIO_2020_Final
                         

   @WindowsAddict (Me) - Ported the above Autoit tool to batch script.
   
   @AveYo aka @BAU     - Snippet to set registry ownership and permission recursively
                         pastebin.com/XTPt0JSC

   @abbodi1406         - Awesome batch script tricks and help.

   @dbenham            - Set buffer height independently of window height
                         https://stackoverflow.com/a/13351373

_________________________________

   IDM Activation Script


____________________________________________________________________________________________________
:txt:

::========================================================================================================================================

:_reset

call :_buffer
echo:
set _error=

reg query "HKCU\Software\DownloadManager" "/v" "Serial" %nul% && (
tasklist /fi "imagename eq idman.exe" | findstr /i "idman.exe" >nul && taskkill /f /im idman.exe
)

if exist "!_appdata!\DMCache\settings.bak" del /s /f /q "!_appdata!\DMCache\settings.bak"

set "_action=call :Delete_Key"
call :Reset

echo:
echo %line%
echo:
if not defined _error (
call :color "IDM Activation / Trial is successfully reset." %Green%
) else (
call :color "Failed to completely reset IDM Activation / Trial." %Red%
)

goto Done

::========================================================================================================================================

:_activate

call :_buffer
echo:
set _error=

if not exist "!IDMan!" (
call :color "IDM (Internet Download Manager) is not Installed." %Red%
echo You can download it from  https://www.internetdownloadmanager.com/download.html
goto Done
)

:: Internet check with internetdownloadmanager.com ping and port 80 test

ping -n 1 internetdownloadmanager.com > nul || (
%_psc% "$t = New-Object Net.Sockets.TcpClient;try{$t.Connect("""internetdownloadmanager.com""", 80)}catch{};$t.Connected" | findstr /i true 1>nul
if not [!errorlevel!]==[0] (
call :color "Unable to connect internetdownloadmanager.com, aborting..." %Red%
goto Done
)
)

echo Internet is connected.

tasklist /fi "imagename eq idman.exe" | findstr /i "idman.exe" >nul && taskkill /f /im idman.exe

if exist "!_appdata!\DMCache\settings.bak" del /s /f /q "!_appdata!\DMCache\settings.bak"

set "_action=call :Delete_Key"
call :Reset

set "_action=call :Count_Key"
call :RegisterIDM

echo:
if defined _derror call :F_Reset & goto Done

set lockedkeys=
set "_action=call :Lock_Key"
echo Locking registry keys...
echo:
call :Action

if not defined _error if [!lockedkeys!] GEQ [7] (
echo:
echo %line%
echo:
call :color "IDM is successfully activated." %Green%
goto Done
)

call :F_Reset

::========================================================================================================================================

:Done

echo %line%
echo:
echo:
if defined Unattended (
echo Exiting in 3 seconds...
if %winbuild% LSS 7600 (ping -n 3 127.0.0.1 > nul) else (timeout /t 3)
exit /b
)
echo Press any key to return...
pause >nul
goto MainMenu

::========================================================================================================================================

:Homepage

cls
echo:
echo:
echo Login is required.
echo:
echo:
timeout /t 3


goto MainMenu

::========================================================================================================================================

:color

%_psc% write-host '%1' -fore '%2' -back '%3'
exit /b

:color1

%_psc% write-host '%1' -fore '%2' -back '%3'  -NoNewline
exit /b

::========================================================================================================================================

:_buffer

::  Set buffer height independently of window height
::  https://stackoverflow.com/a/13351373
::  Written by @dbenham (stackoverflow)

if not defined Unattended (
mode con: cols=93 lines=30
%nul% %_psc% "&{$H=get-host;$W=$H.ui.rawui;$B=$W.buffersize;$B.height=150;$W.buffersize=$B;}"
)
exit /b

::========================================================================================================================================

:F_Reset

echo:
echo %line%
echo:
call :color "Error found, resetting IDM activation..." %Red%
set "_action=call :Delete_Key"
call :Reset
echo:
echo %line%
echo:
call :color "Failed to activate IDM." %Red%
exit /b

::========================================================================================================================================

:Reset

set take_permission=
call :Deletequeue
set take_permission=1
call :Action
call :Addkey
exit /b

::========================================================================================================================================
 
:_rcont

reg add !reg! %nul%
call :_Addkey
exit /b

:RegisterIDM

echo:
echo Applying registration details...
echo:

set "reg=HKCU\SOFTWARE\DownloadManager /v FName /t REG_SZ /d "gamesetup"" & call :_rcont
set "reg=HKCU\SOFTWARE\DownloadManager /v LName /t REG_SZ /d """ & call :_rcont
set "reg=HKCU\SOFTWARE\DownloadManager /v Email /t REG_SZ /d "gamesetup@gmail.com"" & call :_rcont
set "reg=HKCU\SOFTWARE\DownloadManager /v Serial /t REG_SZ /d "FOX6H-3KWH4-7TSIN-Q4US7"" & call :_rcont

echo:
echo Triggering a few downloads to create certain registry keys, please wait...

set "file=!_temp!\temp.html"
set _fileexist=
set _derror=

tasklist /fi "imagename eq idman.exe" | findstr /i "idman.exe" >nul && taskkill /f /im idman.exe

call :Download
call :Download

:: it may take some time to reflect registry keys.
timeout /t 2 >nul

set foundkeys=
call :Action
if [!foundkeys!] GEQ [7] goto _skip

call :Download
call :Download

timeout /t 2 >nul

set foundkeys=
call :Action
if not [!foundkeys!] GEQ [7] set _derror=1

:_skip

echo:
if not defined _derror (
echo Required registry keys were created successfully.
) else (
if not defined _fileexist call :color "Unable to download files with IDM." %Red%
call :color "Failed to create required registry keys." %Red%
call :color "Try again / disable Windows firewall with script options / check Read Me." %Magenta%
)

echo:
tasklist /fi "imagename eq idman.exe" | findstr /i "idman.exe" >nul && taskkill /f /im idman.exe
if exist "!file!" del /f /q "!file!"
exit /b

:Download

set attempt=
if exist "!file!" del /f /q "!file!"
start "" "!IDMan!" /n /d "http://www.internetdownloadmanager.com/" /p "!_temp!" /f temp.html

:Check_file

timeout /t 1 >nul
set /a attempt+=1
if exist "!file!" set _fileexist=1&exit /b
if [!attempt!]==[6] exit /b
goto :Check_file

::========================================================================================================================================

:Deletequeue

echo:
echo Deleting registry keys...
echo:

for %%# in (
""HKCU\Software\DownloadManager" "/v" "FName""
""HKCU\Software\DownloadManager" "/v" "LName""
""HKCU\Software\DownloadManager" "/v" "Email""
""HKCU\Software\DownloadManager" "/v" "Serial""
""HKCU\Software\DownloadManager" "/v" "scansk""
""HKCU\Software\DownloadManager" "/v" "tvfrdt""
""HKCU\Software\DownloadManager" "/v" "radxcnt""
""HKCU\Software\DownloadManager" "/v" "LstCheck""
""HKCU\Software\DownloadManager" "/v" "ptrk_scdt""
""HKCU\Software\DownloadManager" "/v" "LastCheckQU""
"%HKLM%"
) do for /f "tokens=* delims=" %%A in ("%%~#") do (
set "reg="%%~A"" &reg query !reg! %nul% && call :Delete_Key
)

exit /b

::========================================================================================================================================

:Addkey

echo:
echo Adding registry key...
echo:

set "reg="%HKLM%" /v "AdvIntDriverEnabled2""

reg add !reg! /t REG_DWORD /d "1" /f %nul%

:_Addkey

if [!errorlevel!]==[0] (
set "reg=!reg:"=!"
echo Added - !reg!
) else (
set _error=1
set "reg=!reg:"=!"
call :color1 "Failed" %Red% &echo  - !reg!
)
exit /b

::========================================================================================================================================

:Action

if exist %RegData% del /f /q %RegData% %nul%

reg query %CLSID% > %RegData%

%nul% %_psc% "(gc %RegData%) -replace 'HKEY_CURRENT_USER', 'HKCU' | Out-File -encoding ASCII %RegData%"

for /f %%a in (%RegData%) do set "reg=%%a" & call :Scan_Key

if exist %RegData% del /f /q %RegData% %nul%

exit /b

::========================================================================================================================================

:Scan_Key

reg query !reg! 2>nul | findstr /i "LocalServer32 InProcServer32 InProcHandler32" >nul && exit /b

reg query !reg! 2>nul | find /i "H" 1>nul || (
!_action!
exit /b
)

for /f "skip=2 tokens=3" %%a in ('reg query !reg! /ve 2^>nul') do echo %%a|findstr /r "[^0-9]" >nul || (
!_action!
exit /b
)

for /f "skip=2 tokens=3" %%a in ('reg query !reg!\Version /ve 2^>nul') do echo %%a|findstr /r "[^0-9]" >nul || (
!_action!
exit /b
)

for /f "skip=2 tokens=1" %%a in ('reg query !reg! 2^>nul') do echo %%a| findstr /i "MData Model scansk Therad" >nul && (
!_action!
exit /b
)

for /f "skip=2 tokens=3" %%a in ('reg query !reg! /ve 2^>nul') do echo %%a| find /i "+" >nul && (
!_action!
exit /b
)

exit/b

::========================================================================================================================================

:Delete_Key

set _errlvl=
reg delete !reg! /f %nul%
set "_errlvl=!errorlevel!"

if not [!_errlvl!]==[0] if defined take_permission (
call :reg_own "!reg!" preserve S-1-1-0 %nul%
reg delete !reg! /f %nul%
set "_errlvl=!errorlevel!"
)

if [!_errlvl!]==[0] (
set "reg=!reg:"=!"
echo Deleted - !reg!
) else (
set _error=1
set "reg=!reg:"=!"
call :color1 "Failed" %Red% &echo  - !reg!
)

exit /b

::========================================================================================================================================

:Lock_Key

call :reg_own "!reg!" preserve S-1-1-0 S-1-0-0 Deny "FullControl" %nul%

reg delete !reg! /f %nul%

if not [!errorlevel!]==[0] (
set "reg=!reg:"=!"
echo Locked - !reg!
set /a lockedkeys+=1
) else (
set _error=1
set "reg=!reg:"=!"
call :color1 "Failed" %Red% &echo  - !reg!
)

exit /b

::========================================================================================================================================

:Count_Key

set /a foundkeys+=1
exit /b

::========================================================================================================================================

::  A lean and mean snippet to set registry ownership and permission recursively
::  Written by @AveYo aka @BAU
::  pastebin.com/XTPt0JSC

:reg_own

powershell $A='%~1','%~2','%~3','%~4','%~5','%~6';iex(([io.file]::ReadAllText('!_batp!')-split':Own1\:.*')[1])&exit/b:Own1:
$D1=[uri].module.gettype('System.Diagnostics.Process')."GetM`ethods"(42) |where {$_.Name -eq 'SetPrivilege'} #`:no-ev-warn
'SeSecurityPrivilege','SeTakeOwnershipPrivilege','SeBackupPrivilege','SeRestorePrivilege'|foreach {$D1.Invoke($null, @("$_",2))}
$path=$A[0]; $rk=$path-split'\\',2; $HK=gi -lit Registry::$($rk[0]) -fo; $s=$A[1]; $sps=[Security.Principal.SecurityIdentifier]
$u=($A[2],'S-1-5-32-544')[!$A[2]];$o=($A[3],$u)[!$A[3]];$w=$u,$o |% {new-object $sps($_)}; $old=!$A[3];$own=!$old; $y=$s-eq'all'
$rar=new-object Security.AccessControl.RegistryAccessRule( $w[0], ($A[5],'FullControl')[!$A[5]], 1, 0, ($A[4],'Allow')[!$A[4]] )
$x=$s-eq'none';function Own1($k){$t=$HK.OpenSubKey($k,2,'TakeOwnership');if($t){0,4|%{try{$o=$t.GetAccessControl($_)}catch{$old=0}
};if($old){$own=1;$w[1]=$o.GetOwner($sps)};$o.SetOwner($w[0]);$t.SetAccessControl($o); $c=$HK.OpenSubKey($k,2,'ChangePermissions')
$p=$c.GetAccessControl(2);if($y){$p.SetAccessRuleProtection(1,1)};$p.ResetAccessRule($rar);if($x){$p.RemoveAccessRuleAll($rar)}
$c.SetAccessControl($p);if($own){$o.SetOwner($w[1]);$t.SetAccessControl($o)};if($s){$subkeys=$HK.OpenSubKey($k).GetSubKeyNames()
foreach($n in $subkeys){Own1 "$k\$n"}}}};Own1 $rk[1];if($env:VO){get-acl Registry::$path|fl} #:Own1: lean & mean snippet by AveYo

::========================================================================================================================================