@echo off
setlocal DisableDelayedExpansion
rem ** At this point the delayedExpansion should be disabled
rem ** otherwise an exclamation mark in %* will be interpreted as special command
SET SUM_CMD_ARGS=%*

SET SUM_ROOT="%~dp0"

SET DRIVE="%~d0"

rem remove trailing back slash
IF "!SUM_ROOT:~-1!"=="\" SET SUM_ROOT=!SUM_ROOT:~0,-1!

SET dstpath="!SUM_ROOT!"

setlocal EnableDelayedExpansion

SET REMOTE=0
SET SERVICERUNNING=0
SET ERRORCODE=0

rem Windows server 2008 and earlier are no longer supported starting SUM 8.0
ver | find "Version 5"
if %errorlevel% EQU 0 (
	echo Smart Update Manager 8.0 supports Windows Server 2008 R2 and later. Use HP SUM 7.6 for older Windows versions.
	set ERRORCODE=-4
	pause
	goto :Exit
)

ver | find "Version 6.0"
if %errorlevel% EQU 0 (
echo Smart Update Manager 8.0 supports Windows Server 2008 R2 and later. Use HP SUM 7.6 for older Windows versions.
	set ERRORCODE=-4
	pause
	goto :Exit
)

IF "!TMPDIR!"=="" (
	SET TMPDIR=%temp%
) ELSE (
	echo TMPDIR is set to !TMPDIR!
)


rem Check if any of the following switches were passed as arguments.  
rem They will not yet require a copy of the SUM Files if remote.
rem check for: /v, /version (version information)
rem check for: /h, /?, /help (help)

rem check for silent as it is a different mode for SUM
rem check for: /s, /silent

rem Initialize
SET INPUTFILEPATH=
SET USELOCATION=0
SET LEGACYMODE=0
SET ERRORCODE=0
SET VERSION=0
SET HELP=0

:loop
IF NOT "%~1"=="" (

rem Get if silent flag is set. Treat it exactly like express_install.
    IF "%~1"=="/s" SET LEGACYMODE=1
    IF "%~1"=="/silent" SET LEGACYMODE=1

rem Get if express_install flag is set. Treat it exactly like silent mode.
    IF "%~1"=="/express_install" SET LEGACYMODE=1

rem Handle working directory
    IF "%~1"=="/use_location" (
        SET USELOCATION=1
        SHIFT
    )

rem Handle input file
    IF "%~1"=="/inputfile" (
        SET INPUTFILEPATH="%~2"
        SHIFT
    )
rem handle logdir	
	IF "%~1"=="/logdir" (
        SHIFT
    )
rem Handle version
    IF "%~1"=="/v" SET VERSION=1
    IF "%~1"=="/version" SET VERSION=1

rem Handle help
    IF "%~1"=="/h" SET HELP=1
    IF "%~1"=="/help" SET HELP=1
    IF "%~1"=="/?" SET HELP=1

    SHIFT
    GOTO :loop
)

IF !VERSION! NEQ 0 (
	goto :run
)
IF !HELP! NEQ 0 (
	goto :run
)

rem check whether it is Virtual mapped Drive 
rem updates method to handle different locale. 
FOR /F "tokens=*" %%A IN ('"fsutil fsinfo drivetype"" "!DRIVE!""') do (
 	SET drvchk=%%A

	rem check if drive contains cd-rom (case insensitve)
	if /i NOT "!drvchk!"=="!drvchk:CD-ROM=!" (
            echo %~d0 is a CD-ROM Drive
            set REMOTE=1
            set dstpath="%LOCALAPPDATA%\localsum"
            goto :run
      )
)

rem check whether it is N/W mapped Drive or UNC path
rem SUM_ROOT will contain eg: "Z:\packages" or "\\", hence taking the 2nd and 3rd Character to match it with the output of net use.
IF "!SUM_ROOT:~1,2!"=="\\" (
    echo !SUM_ROOT! is a remote UNC path
    set REMOTE=1
    set dstpath="%LOCALAPPDATA%\localsum"
	goto :run
) ELSE (
    for /f "skip=6 tokens=2" %%d in ('net use') do (
        if /i "!SUM_ROOT:~1,2!"=="%%d" (
            echo !SUM_ROOT! is a Network Mapped Drive
            set REMOTE=1
            set dstpath="%LOCALAPPDATA%\localsum"
            goto :run
        )
    )
)

:run
setlocal DisableDelayedExpansion
set newcmdcmdline="%cmdcmdline:"=-%"
set withincmd=1
echo %newcmdcmdline% | find /i "cmd /c --%~dpf0%-"
if %errorlevel% EQU 0 set withincmd=0
rem if %withincmd% EQU 0 echo This batch-file: %~dpf0 was executed directly (from Windows Explorer, ...).
rem if %withincmd% EQU 1 echo This batch-file: %~dpf0 was executed from within a Command Prompt
setlocal EnableDelayedExpansion
rem Select 32-bit or 64-bit
SET HostIs64Bit=%ProgramFiles(x86)%
IF "%HostIs64Bit%"=="" (
    set SUM_ARCH=x86
) ELSE (
    set SUM_ARCH=x64
)


rem If help or version commands were detected, then skip the copy and execute SUM


IF %REMOTE% EQU 0 GOTO :runsum


rem Check if there's an existing sum service running..
tasklist /FI "IMAGENAME eq sum_service_%SUM_ARCH%.exe" 2>NUL | find /I /N "sum_service_%SUM_ARCH%.exe" >NUL

IF %ERRORLEVEL% NEQ 0 (
	GOTO :copyfiles
) ELSE (
    SET SERVICERUNNING=1
	IF %LEGACYMODE% EQU 0 (
		GOTO :copyfiles
	) ELSE (
        rem ONLY if a silent switch is detected, do not allow running of sum again. 
        rem Otherwise, let it through as it could be interactive commands.
        echo An existing SUM session is detected.
        set ERRORCODE=-4
        goto :WrapUp
	)
)

	
:copyfiles
SET SUM_VERSION_EXIST=0
IF EXIST %SUM_ROOT%sum*_b*.txt (
	FOR /F "delims=" %%a IN ('dir /b !SUM_ROOT!\"sum*_b*.txt"') DO SET SUM_VERSION_FILE=!params!%%a
	IF NOT "!SUM_VERSION_FILE!"=="" (
		IF EXIST !dstpath!\!SUM_VERSION_FILE! (
			SET SUM_VERSION_EXIST=1
		) ELSE (
			rd /s /q !dstpath! 2> NUL
		)
	)
)

IF %SUM_VERSION_EXIST% EQU 0 (
	echo Copying SUM files from !SUM_ROOT! to !dstpath!
	IF NOT EXIST !dstpath! (        
        md !dstpath! 
        
        rem Check if the folder is now present.
        IF NOT EXIST !dstpath! (
            echo Could not create the temporary directory !dstpath!
            SET ERRORCODE=-4
            goto :WrapUp
        )
    )

    xcopy /s /y /i /q "!SUM_ROOT!\%SUM_ARCH%" "!dstpath!\%SUM_ARCH%" 2>NUL
    IF !ERRORLEVEL! NEQ 0 (
	    IF !SERVICERUNNING! EQU 0  (
			SET ERRORCODE=-4
			goto :WrapUp
		)
    )

    xcopy /s /y /i /q "!SUM_ROOT!\assets" "!dstpath!\assets"
    IF !ERRORLEVEL! NEQ 0 (
        SET ERRORCODE=-4
        goto :WrapUp
    )
   
    xcopy /s /y /i /q "!SUM_ROOT!\cygwin" "!dstpath!\cygwin"
    IF !ERRORLEVEL! NEQ 0 (
        SET ERRORCODE=-4
        goto :WrapUp
    )

    xcopy /y /i /q "!SUM_ROOT!masterdependency.xml" "!dstpath!\"
    IF !ERRORLEVEL! NEQ 0 (
        SET ERRORCODE=-4
        goto :WrapUp
    )

    xcopy /y /i /q "!SUM_ROOT!platformdependency.xml" "!dstpath!\"
    IF !ERRORLEVEL! NEQ 0 (
        SET ERRORCODE=-4
        goto :WrapUp
    )
	
	xcopy /y /i /q "!SUM_ROOT!gatherlogs.bat" "!dstpath!\"
    IF !ERRORLEVEL! NEQ 0 (
        SET ERRORCODE=-4
        goto :WrapUp
    )
	IF NOT "%SUM_VERSION_FILE%"=="" (
		xcopy /y /i /q "!SUM_ROOT!!SUM_VERSION_FILE!" "!dstpath!\"
	)

    IF EXIST "%INPUTFILEPATH%" xcopy /y /i /q "%INPUTFILEPATH%" "!dstpath!\"
    IF !ERRORLEVEL! NEQ 0 (
        SET ERRORCODE=-4
        goto :WrapUp
    )
)

    rem If working directory is not set, and it is a read-only then append use_location with the mount point path
    IF %LEGACYMODE% EQU 1 (
        IF %USELOCATION% NEQ 1 (
            SET "SUM_CMD_ARGS=!SUM_CMD_ARGS! /use_location "!SUM_ROOT!
        )
    )


:runsum
set SUM_BIN="!dstpath!\%SUM_ARCH%\sum_bin_%SUM_ARCH%.exe"

IF NOT EXIST %SUM_BIN% (
    @echo Unable to locate %SUM_BIN%
    IF %withincmd% EQU 0 (
        call :delay
    )
    set ERRORCODE=-4
    goto :Exit
)
	
rem Remove localsum folder if cleanup_onexit or cleanupall_onexit
SET REMOVE_LOCALPATH = 0
FOR %%a IN (%*) DO (
  IF /I "%%a"=="/cleanup_onexit" SET REMOVE_LOCALPATH=1
  IF /I "%%a"=="/cleanupall_onexit" SET REMOVE_LOCALPATH=1
)

%SUM_BIN% !SUM_CMD_ARGS!

set ERRORCODE=%ERRORLEVEL%

rem the acutal binary should have displayed an error
rem message.  We still want to delay to allow
rem people who started by clicking on the icon
rem a chance to see the message
:WrapUp
IF %ERRORCODE% NEQ 0 (
    if %withincmd% EQU 0 (
        call :delay
    )
    goto :Exit
)    

goto :Exit

:delay
where ping > nul 2>&1
IF %ERRORLEVEL% NEQ 0 (
    pause
) else (
    @echo Pausing for 10 seconds ...
    ping -n 11 127.0.0.1 > nul
)
goto :EOF

:Exit
IF %REMOTE% EQU 1 (
	IF "%SUM_REMOVE_TEMP_FILES%"=="true" (
		echo SUM_REMOVE_TEMP_FILES set true, removing sum files
		rd /s /q !dstpath! 2> NUL
	)
	
	IF !REMOVE_LOCALPATH! EQU 1 (
		echo cleanup_onexit or cleanupall_onexit is set, removing files at !dstpath!
		rd /s /q !dstpath! 2> NUL
	)
)
exit /b %ERRORCODE%
