@echo off
REM ==============================================================
REM start=DS WinPE startup support routines
REM Version=6.9 SP4/7.1 SP1
REM --------------------------------------------------------------
if not defined log if not defined __log if exist "%systemdrive%\__log__" set __log=%~dpn0.log
if defined log if not defined __log set __log=true& call %0 %* >>"%~dp0%log%" & set __log=& goto :eof
if defined echo (echo on) else if exist "%systemdrive%\__echo__" (echo on) else (echo off)
set __dbg=rem & if defined debug (set __dbg=) else if exist "%systemdrive%\__debug__" (set __dbg=) else (set __dbg=rem)


REM ==============================================================
REM main=Main entry point
REM	1 = Routine/label name to call
REM	2... = Parameters
REM	return = <depends on label>
REM --------------------------------------------------------------
:main
if "%~1" == "" goto :eof
set _label=%~1
if "%_label:~0,1%" == ":" set _label=%_label:~1%
if exist "%systemdrive%\-%_label%.cmd" (
  set _label="%systemdrive%\-%_label%.cmd"
) else if exist "%systemdrive%\-%_label%.bat" (
  set _label="%systemdrive%\-%_label%.bat"
) else (
  set _label=:%_label%
)

rem shift
rem shift
rem call %_label% %0 %1 %2 %3 %4 %5 %6 %7 %8 %9
%__dbg% echo Calling "%_label%":
call :get-params _params 1 %*
rem %__dbg% echo params=^"%_params%^"
call %_label% %_params%

if not defined _result set _result=%errorlevel%
set _label=
set _params=
goto :eof


REM ==============================================================
REM test=Test entry point
REM --------------------------------------------------------------
:test
echo At test point...
echo 0=%0
echo 1=%1
echo 2=%2
echo 3=%3
echo 4=%4
echo 5=%5
echo 6=%6
echo 7=%7
echo 8=%8
echo 9=%9
goto :eof


REM ==============================================================
REM call=Call a routine
REM	1 = Routine/label name to call
REM	2... = Parameters <depends on routine>
REM	return = <depends on routine>
REM --------------------------------------------------------------
:call
rem for %%i in (%path%) do if exist "%%i\startutl.bat" set utl=%%i\startutl.bat
set _label=%~1
if "%_label:~0,1%" == ":" set _label=%_label:~1%
call %utl%:call-fnd "%_label%" _label file "%systemdrive%\-%_label%.cmd" "%systemdrive%\-%_label%.bat" _label "%systemdrive%\startup.bat" "%~dp0startutl.bat" "%~f0"
shift&shift
if defined _label call %_label% %0 %1 %2 %3 %4 %5 %6 %7 %8 %9
set _label=
goto :eof


REM ==============================================================
REM call-fnd=Find the label/file to call
REM	1 = label to find
REM	2 = name of environment variable to set to the return value
REM	3... = options:
REM		"file" to search for specified file
REM		"label" to search file for "label"
REM		<other> a file to search for (file), or to search in (label)
REM	return = set env variable in parameter 2 to the command to call
REM --------------------------------------------------------------
:call-fnd
if "%~1" == "" goto :eof
setlocal
set label=%~1
set rtn=%2
if "%label:~0,1%" == ":" set label=%label:~1%
set type=file
set cmd=
shift /1

:call-loop
shift /1
%__dbg% echo i=%1
rem See what the next parameter is - "" exits the loop
if "%1" == "" (
  goto call-done
) else if /i "%1" == "file" (
  rem Set "file" mode for all following parameters
  set type=%1
) else if /i "%1" == "label" (
  rem Set "label" mode for all following parameters
  set type=%1
) else if /i "%type%" == "file" (
  rem See if the specified file exists
  if exist "%~1" (
    rem That's it - call this file
    set cmd=%~1
  )
) else if /i "%type%" == "label" (
  rem Search the specified file for the label
rem   findstr /b /e /l /i /c:":%label%" "%~1" >nul 2>nul
rem   if not errorlevel 1 (
  set fnd=
  for /f "usebackq eol=- tokens=* delims=|" %%a in (`find /i ^":%label%^" ^"%~1^"`) do if "%%a" == ":%label%" set fnd=true
  if defined fnd (
    rem Found the label in the file - call the label in this file
    if "%~1" == "%~f0" (
      rem It is this same file, so don't include the file name
      set cmd=:%label%
    ) else (
      set cmd=%~1 :%label%
    )
  )
)
if not defined cmd goto call-loop

:call-done
if not defined cmd echo ** Unable to locate '%label%' **
endlocal & set %rtn%=%cmd%
goto :eof


REM ==============================================================
REM get-params=Get command line parameters
REM	"1" = env variable to place the parameters into (defaults to prms)
REM	"2" = number of leading parameters to skip (defaults to 0)
REM	3... = parameters
REM	return = set env variable in parameter 1 to the list of parameters
REM --------------------------------------------------------------
:get-params
setlocal
set eprms=%~1& shift
set cnt=%~1& shift
if "%eprms%" == "" set eprms=prms
if "%cnt%" == "" set cnt=0

for /l %%v in (1,1,%cnt%) do shift
set prms=
set /a i=1

:params-loop
%__dbg% if not ^"%1^" == ^"^" echo.  %i% = "%1"
if not ^"%1^" == ^"^" set prms=%prms%%1 & set /a i=i+1 & shift & goto params-loop

set p=%prms:~-1%
if "%p%" == " " set prms=%prms:~0,-1%
endlocal & set %eprms%=%prms%
goto :eof


REM ==============================================================
REM get-tagged-params=Get tagged parameters
REM	1 = Env variable prefix for parameter values
REM	2... = Parameters in form tag=value
REM	return = Env variables prefixed with parameter 1
REM --------------------------------------------------------------
:get-tagged-params
set pfx=%~1
shift /1

:get-tagged-loop
if "%~1" == "" goto get-tagged-done
for /f "tokens=1* delims==" %%v in ("%~1") do set %pfx%%%v=%%w& set single=%%w
if "%single%" == "" for /f "tokens=1* delims==" %%v in ("%~1=%~2") do shift /1 & set %pfx%%%v=%%w
shift /1
goto get-tagged-loop

:get-tagged-done
set single=
set pfx=
goto :eof


REM ==============================================================
:show-params
setlocal EnableDelayedExpansion EnableExtensions
echo Arg[*] = '%*'
set/a i=0
:show-params1
if "%0" == "" endlocal & goto :eof
echo Arg[%i%] = '%0'
set/a i=i+1
shift
goto show-params1


REM ==============================================================
:show-paramsx
echo Arg[*] = '%*'
set/a i=0
:show-paramsx1
if not ^"%1^" == ^"^" echo.  Arg[%i%] = '%1' & set /a i=i+1 & shift & goto show-params1
goto :eof


REM ==============================================================
REM tokenize=Separate tokens on a delimiter
REM	1 = String to tokenize
REM	2 = Delimiter to tokenize on
REM	3 = Env variable prefix for tokens
REM	4 = First variable number to use
REM	return = Env variables prefixed with parameter 3
REM --------------------------------------------------------------
:tokenize
set dlm=^|& if not "%~2" == "" set dlm=^%~2
set pfx=v_& if not "%~3" == "" set pfx=%~3
set i=1&    if not "%~4" == "" set i=%~4
set /a i=i-1

if "%~4" == "" for /l %%i in (1,1,26) do set %pfx%%%i=& set %pfx%0%%i=
for /f "tokens=1-25* delims=%dlm%" %%a in ("%~1") do (
  set/a i=i+1& set %pfx%!i!=%%a&if not "%%a" == "" set %pfx%0=!i!
  set/a i=i+1& set %pfx%!i!=%%b&if not "%%b" == "" set %pfx%0=!i!
  set/a i=i+1& set %pfx%!i!=%%c&if not "%%c" == "" set %pfx%0=!i!
  set/a i=i+1& set %pfx%!i!=%%d&if not "%%d" == "" set %pfx%0=!i!
  set/a i=i+1& set %pfx%!i!=%%e&if not "%%e" == "" set %pfx%0=!i!
  set/a i=i+1& set %pfx%!i!=%%f&if not "%%f" == "" set %pfx%0=!i!
  set/a i=i+1& set %pfx%!i!=%%g&if not "%%g" == "" set %pfx%0=!i!
  set/a i=i+1& set %pfx%!i!=%%h&if not "%%h" == "" set %pfx%0=!i!
  set/a i=i+1& set %pfx%!i!=%%i&if not "%%i" == "" set %pfx%0=!i!
  set/a i=i+1& set %pfx%!i!=%%j&if not "%%j" == "" set %pfx%0=!i!
  set/a i=i+1& set %pfx%!i!=%%k&if not "%%k" == "" set %pfx%0=!i!
  set/a i=i+1& set %pfx%!i!=%%l&if not "%%l" == "" set %pfx%0=!i!
  set/a i=i+1& set %pfx%!i!=%%m&if not "%%m" == "" set %pfx%0=!i!
  set/a i=i+1& set %pfx%!i!=%%n&if not "%%n" == "" set %pfx%0=!i!
  set/a i=i+1& set %pfx%!i!=%%o&if not "%%o" == "" set %pfx%0=!i!
  set/a i=i+1& set %pfx%!i!=%%p&if not "%%p" == "" set %pfx%0=!i!
  set/a i=i+1& set %pfx%!i!=%%q&if not "%%q" == "" set %pfx%0=!i!
  set/a i=i+1& set %pfx%!i!=%%r&if not "%%r" == "" set %pfx%0=!i!
  set/a i=i+1& set %pfx%!i!=%%s&if not "%%s" == "" set %pfx%0=!i!
  set/a i=i+1& set %pfx%!i!=%%t&if not "%%t" == "" set %pfx%0=!i!
  set/a i=i+1& set %pfx%!i!=%%u&if not "%%u" == "" set %pfx%0=!i!
  set/a i=i+1& set %pfx%!i!=%%v&if not "%%v" == "" set %pfx%0=!i!
  set/a i=i+1& set %pfx%!i!=%%w&if not "%%w" == "" set %pfx%0=!i!
  set/a i=i+1& set %pfx%!i!=%%x&if not "%%x" == "" set %pfx%0=!i!
  set/a i=i+1& set %pfx%!i!=%%y&if not "%%y" == "" set %pfx%0=!i!
  set/a i=i+1& set %pfx%!i!=%%z&if not "%%z" == "" set %pfx%0=!i!
  set z=%%z& if not "!z:%dlm%=!" == "%%z" call :tokenize "%%z" "%dlm%" "%pfx%" !i!
)

set dlm=
set pfx=

goto :eof


REM ==============================================================
REM get-output=Get the output from a program
REM	"1" = Command to run
REM	2   = env variable to place the output into
REM	"3" = Multiple item separator (defaults to ",")
REM	"4" = Comment character in outout to ignore lines (defaults to ";")
REM	return = sets env variable in %2 to output of that program
REM --------------------------------------------------------------
:get-output
setlocal EnableDelayedExpansion EnableExtensions
if "%~2" == "" goto get-output-done
set eval=%~2
set sep=%~3& if "!sep!" == "" set sep=,
set eol=%~4& if "!eol!" == "" set eol=;
rem echo cmd='%1'
rem pause
for /f "usebackq eol=%eol% tokens=1* delims=" %%a in (`%~1`) do set val=%val%%sep%%%a
if "%val%" == "" (set ret=1) else (set ret=0)
if not "%val%" == "" if "%val:~0,1%" == "%sep%" (
  set val=%val:~1%
)
endlocal & set %eval%=%val%& exit /b %ret%
:get-output-done
goto :eof


REM ==============================================================
REM get-server-ip=Get server and IP address(es)
REM	1 = Combined server/IP string
REM	2 = Env variable to return server name in
REM	3 = Env variable to return server ip(s) in
REM	return = Env variables set with server and ip address
REM --------------------------------------------------------------
:get-server-ip
setlocal EnableDelayedExpansion EnableExtensions

set esvr=svr& if not "%~2" == "" set esvr=%~2
set eips=ips& if not "%~3" == "" set eips=%~3

call :tokenize "%~1" "|" v_

%__dbg% echo server name="%v_1%%v_01%"
%__dbg% echo server IPs="%v_2%%v_02%"

endlocal & set %esvr%=%v_1%%v_01%& set %eips%=%v_2%%v_02%
goto :eof


REM ==============================================================
REM get-processor=Get processor type from the environment
REM	1 = Env variable to return processor type in (defaults to prc)
REM	2 = Default value to use if unable to determine processor architecture
REM	return = Env variable set with processor architecture type (x86, x64, ia64)
REM --------------------------------------------------------------
:get-processor
setlocal EnableDelayedExpansion EnableExtensions

set eprc=prc& if not "%~1" == "" set eprc=%~1

if /i "%PROCESSOR_ARCHITECTURE%" == "x86"   set prc=x86
if /i "%PROCESSOR_ARCHITECTURE%" == "AMD64" set prc=x64
if /i "%PROCESSOR_ARCHITECTURE%" == "IA64"  set prc=ia64
if not defined prc set prc=%~2

%__dbg% echo Processor architecture="%prc%"

endlocal & set %eprc%=%prc%
goto :eof


REM ==============================================================
REM get-osprocessor=Get OS processor type from the environment
REM	1 = Env variable to return processor type in (defaults to prc)
REM	return = Env variable set with processor architecture type (x86, amd64, ia64)
REM --------------------------------------------------------------
:get-osprocessor
setlocal EnableDelayedExpansion EnableExtensions

set eprc=prc& if not "%~1" == "" set eprc=%~1

set prc=%PROCESSOR_ARCHITECTURE%

%__dbg% echo Processor OS architecture="%prc%"

endlocal & set %eprc%=%prc%
goto :eof


REM ==============================================================
REM get-winpe=Get type of winpe that is running (1 or 2)
REM	1 = Env variable to return type in (defaults to winpe)
REM	return = Env variable set with winpe type (1 or 2)
REM --------------------------------------------------------------
:get-winpe
setlocal EnableDelayedExpansion EnableExtensions

set ewinpe=winpe& if not "%~1" == "" set ewinpe=%~1

set winpe=
call :is-winpe1
if errorlevel 1 set winpe=4.0
call :is-winpe3
if errorlevel 1 set winpe=1

%__dbg% echo WinPE type=%winpe%

endlocal & set %ewinpe%=%winpe%
goto :eof


REM ==============================================================
REM is-winpe1=See if running in WinPE 1.x
REM	return = Exit code is 0 if in WinPE 1.x
REM --------------------------------------------------------------
:is-winpe1
if exist "%systemdrive%\windows" exit /b 1
if exist "%systemroot%\system32\wpeinit.*" exit /b 1
exit /b 0
goto :eof


REM ==============================================================
REM is-winpe3=See if running in WinPE 2.x
REM	return = Exit code is 0 if in WinPE 2.x
REM --------------------------------------------------------------
:is-winpe3
if not exist "%systemdrive%\windows" exit /b 1
if not exist "%systemroot%\system32\wpeinit.*" exit /b 1
exit /b 0
goto :eof


REM ==============================================================
REM is-boot=See if this is a certain type of boot environemnt.
REM	1 = The boot environment type to check for (one of: USB/DISK, PXE, CDROM, DVD, HBW, EBW, FLOPPY, FOLDER/DIR, FILES)
REM	2 = The current boot environment (defaults to %ALTIRIS_BOOTDEVICE%)
REM	3 = The number of characters to compare (defaults to all, 0=all)
REM	return = Exit code is 0 if successful
REM --------------------------------------------------------------
:is-boot
setlocal EnableDelayedExpansion EnableExtensions
set __dev=%ALTIRIS_BOOTDEVICE%& if not "%~2" == "" set __dev=%~2
set __bd=%~1
set __n=25& if not "%~3" == "" set __n=%~3& if "!__n!" == "0" set __n=25
if not defined __bd  exit /b 1
if not defined __dev exit /b 1
if /i "%__bd%" == "%__dev%" exit /b 0
if /i "!__bd:~0,%__n%!" == "!__dev:~0,%__n%!" exit /b 0
exit /b 1
goto :eof

:is-boot-usb
:is-boot-disk
call :is-boot usb "%~1" "%~2"
if errorlevel 1 call :is-boot disk "%~1" "%~2"
goto :eof

:is-boot-pxe
call :is-boot pxe "%~1" "%~2"
goto :eof

:is-boot-cdrom-dvd
call :is-boot cdrom "%~1" "%~2"
if errorlevel 1 call :is-boot dvd "%~1" "%~2"
goto :eof

:is-boot-cdrom
call :is-boot cdrom "%~1" "%~2"
goto :eof

:is-boot-dvd
call :is-boot dvd "%~1" "%~2"
goto :eof

:is-boot-hbw
call :is-boot hbw "%~1" "%~2"
goto :eof

:is-boot-ebw
call :is-boot ebw "%~1" "%~2"
goto :eof

:is-boot-floppy
call :is-boot floppy "%~1" "%~2"
goto :eof

:is-boot-folder
:is-boot-dir
call :is-boot folder "%~1" "%~2"
if errorlevel 1 call :is-boot dir "%~1" "%~2"
goto :eof

:is-boot-files
call :is-boot files "%~1" "%~2"
goto :eof


REM ==============================================================
REM is-mode=See if this is a certain type of bdc mode.
REM	1 = The bdc mode to check for (one of: DS, NS, RD, GS)
REM	2 = The current bdc mode (defaults to %_BDC_mode%)
REM	return = Exit code is 0 if successful
REM --------------------------------------------------------------
:is-mode
set __mode=%_BDC_mode%& if not "%~2" == "" set __mode=%~2

if "%~1" == "" set __mode=& exit /b 1
if not defined __mode set __mode=& exit /b 1
if /i "%~1" == "%__mode%" set __mode=& exit /b 0
set __mode=
exit /b 1
goto :eof

:is-mode-ds
call :is-mode ds %~1
goto :eof

:is-mode-ns
call :is-mode ns %~1
goto :eof

:is-mode-rd
call :is-mode rd %~1
goto :eof

:is-mode-gs
call :is-mode gs %~1
goto :eof


REM ==============================================================
REM DeleteEnv=Delete environment variables
REM	1 = Prefix of environment variables to delete (cannot be empty)
REM	return = ??
REM --------------------------------------------------------------
:DeleteEnv
if not "%~1" == "" for /f "usebackq tokens=1* delims==" %%v in (`set ^>nul 2^>nul %~1`) do set %%v=
goto :eof


REM ==============================================================
REM startup=Run applications in specified folder
REM	1 = wildcard of files/applications to run
REM	2 = file extension of files to exclude (eg "reg")
REM	3... = options:
REM		"wait" to wait for each application to finish
REM		"echo" to display command line being started
REM		"call" to call batch files rather than launch them
REM		"hide" to hide window from application (if possible)
REM		"local" to use local environment variables
REM		"" is the end of the options
REM	... = Any other user supplied parameters may be specified
REM	return = <none>
REM --------------------------------------------------------------
:startup
rem setlocal EnableDelayedExpansion EnableExtensions
for /f "usebackq tokens=* delims=" %%i in (`dir /b /a-d /one ^"%~1^" 2^>nul`) do call :startup-file "%~dp1" "%%i" "%~2" "%~3" "%~4" "%~5" "%~6" "%~7" "%~8" "%~9"
rem endlocal
goto :eof

:startup-file
REM 1 = path
REM 2 = file
REM 3 = exclude extension
REM 4... = options
rem setlocal EnableDelayedExpansion EnableExtensions
set ext=%~x2
set ext=%ext:~1%
if /i "%ext%" == "%~3" goto startup-done

:startup-loop
if "%~4" == "" goto startup-run
if /i "%~4" == "wait" set wait=/wait
if /i "%~4" == "hide" set hide=/min
if /i "%~4" == "call" set call=true
if /i "%~4" == "echo" set show=true
shift /4
goto startup-loop

:startup-run
if /i "%ext%" == "reg" (
  set cmd=regedit /s "%~1%~2"
  set call=
) else if /i "%ext%" == "cmd" (
  rem set cmd=/b cmd /q /v:on /e:on /c "%~1%~2"
  set cmd=cmd /q /v:on /e:on /c call "%~1%~2"
) else if /i "%ext%" == "bat" (
  rem set cmd=/b cmd /q /v:on /e:on /c "%~1%~2"
  set cmd=cmd /q /v:on /e:on /c call "%~1%~2"
) else (
  set cmd="%~1%~2"
  set call=
)
set ext=
if defined call (
  if defined show echo.  ^>call "%~1%~2"...
  rem call "%~1%~2" %~3 %~4 %~5 %~6 %~7 %~8 %~9
  call "%~1%~2"
) else (
  if defined show echo.  ^>start %wait% %hide% %cmd%...
  start "%~2" /d "%~1" %wait% %hide% %cmd%
  if defined hide "%systemdrive%\wndctl" -hide "%~2"
)

:startup-done
set cmd=
set wait=
set hide=
set call=
set show=
rem endlocal
goto :eof


REM ==============================================================
REM net-start=Initialize WinPE and the network
REM --------------------------------------------------------------
:net-start
setlocal EnableDelayedExpansion EnableExtensions
echo Starting the network...

rem WinPE1.x...
call :is-winpe1
if not errorlevel 1 (
  if defined _UseFactoryWinpe (
    echo.  Using "factory -winpe" mode.
    factory -winpe
  ) else (
    echo.  Using "factory -minint" mode.
    Regsvr32 /s netcfgx.dll
    Factory -minint
    Netcfg -winpe
    Net start dhcp
    Net start lmhosts
  )
  endlocal
  goto :eof
)

rem WinPE2.x...
call :drvload "%systemdrive%\drvload.lst" "%systemroot%\inf"
if exist "%systemdrive%\unattend.xml" (
  echo Using unattend.xml...
  wpeinit -unattend="%systemdrive%\unattend.xml"
) else (
  wpeinit
  if exist "%ALTIRIS_BOOTDISK%\nicinfo.ini" (
    echo Using nicinfo.ini...
    call :net-nicinfo "%systemdrive%\staticip.bat" 1 "%ALTIRIS_BOOTDISK%\nicinfo.ini"
    if exist "%systemdrive%\staticip.bat" (
rem      start "Configure Static IP" /wait /min "%systemdrive%\staticip.bat"
      call "%systemdrive%\staticip.bat" >"%systemdrive%\staticip.log"
    )
  ) else if exist "%systemdrive%\staticip.bat" (
    echo Using staticip.bat...
rem    start "Configure Static IP" /wait /min "%systemdrive%\staticip.bat"
    call "%systemdrive%\staticip.bat" >"%systemdrive%\staticip.log"
  ) else if defined _UseStaticIP (
    echo Using static IP %_ClientIP%/%_ClientSubnet%/%_ClientGateway%...
    netcfg -winpe
    wpeutil InitializeNetwork
    netsh interface ipv4 set address   name="%_ClientInterface%" source=static addr=%_ClientIP% mask=%_ClientSubnet% gateway=%_ClientGateway% gwmetric=1
    netsh interface ipv4 set dnsserver name="%_ClientInterface%" source=static addr=%_ClientDns1%
    netsh interface ipv4 add dnsserver "name=%_ClientInterface%"               addr=%_ClientDns2% index=2
    await 2
rem    exit
  ) else (
    echo Using Dynamic IP...
  )
)

echo Configuring WinPE firewall...
if defined _EnableFirewall (
  echo.  Firewall enabled.
  wpeutil EnableFireWall >nul
) else (
  echo.  Firewall disabled.
  wpeutil DisableFireWall >nul
)

endlocal
goto :eof

rem WinPE2.x...
:net-start2
setlocal EnableDelayedExpansion EnableExtensions
echo Starting the network...


endlocal
goto :eof


REM ==============================================================
REM net-nicinfo=Get the IP properties from netfino.ini
REM	"1" = File to write static IP settings to (defauls to x:\staticip.bat)
REM	2   = Number of IP's per nic to process (defaults to 1)
REM	"3" = Path to nicinfo.ini file to process (defaults to x:\nicinfo.ini)
REM	"4" = Name of file to get ipconfig info from (defaults to runnng ipconfig command)
REM	return = Writes static IP info into file %1
REM --------------------------------------------------------------
:net-nicinfo
setlocal EnableDelayedExpansion EnableExtensions
set staticip=%~1& if "!staticip!" == "" set staticip=%systemdrive%\staticip.bat
set m=%~2& if "!m!" == "" set m=1
set nicinfo=%~3& if "!nicinfo!" == "" set nicinfo=%systemdrive%\nicinfo.ini
set ipconfig=%~4

if exist "%staticip%" del "%staticip%"

set vals=& call :ini-read "%nicinfo%" "nics" "" vals
call :tokenize "%vals%" "," ___nic 1
for /l %%i in (1,1,%___nic0%) do if not "!___nic%%i!!___nic0%%i!" == "" (
  set mac=!___nic%%i!!___nic0%%i!
  for /l %%j in (1,1,%m%) do (
    set n=& if not "%%j" == "1" set n=%%j
    set dhcp=& call :ini-read "%nicinfo%" "!mac!" "dhcp!n!"       dhcp
    set ipv4=& call :ini-read "%nicinfo%" "!mac!" "ipaddr!n!"     ipv4
    set mask=& call :ini-read "%nicinfo%" "!mac!" "netmask!n!"    mask
    set gway=& call :ini-read "%nicinfo%" "!mac!" "gateway!n!"    gway
    set dns=&  call :ini-read "%nicinfo%" "!mac!" "dnsserver!n!"  dns
    set wins=& call :ini-read "%nicinfo%" "!mac!" "winsserver!n!" wins
    set sfx=&  call :ini-read "%nicinfo%" "!mac!" "dnssuffix!n!"  sfx
    if not "!ipv4!" == "" call :net-nicinfo2 "%staticip%" "%ipconfig%" %%j "!mac!" "!dhcp!" "!ipv4!" "!mask!" "!gway!" "!dns!" "!wins!" "!sfx!"
  )
)
call :deleteenv "___nic"

endlocal
goto :eof

:net-nicinfo2
setlocal EnableDelayedExpansion EnableExtensions
set staticip=%~1& shift & if "!staticip!" == "" set staticip=%systemdrive%\staticip.bat
set ipconfig=%~1& shift
set n=%~1&        shift
set mac=%~1&      shift
set dhcp=%~1&     shift
set ipv4=%~1&     shift
set mask=%~1&     shift
set gway=%~1&     shift
set dns=%~1&      shift
set wins=%~1&     shift
set sfx=%~1&      shift

if /i not "%dhcp%" == "false" endlocal & goto :eof

if "%ipconfig%" == "" (
  if "%n%" == "1" (
    echo Looking for nic with mac='%mac%'...
  ) else (
    echo Looking for nic with mac='%mac%'[%n%]'...
  )
) else (
  if "%n%" == "1" (
    echo Looking for nic with mac='%mac%' in '%ipconfig%'...
  ) else (
    echo Looking for nic with mac='%mac%'[%n%] in '%ipconfig%'...
  )
rem echo Looking in '%ipconfig%' for nic with mac='%mac%', dhcp='%dhcp%', ipv4='%ipv4%', mask='%mask%', gway='%gway%', dns='%dns%', wins='%wins%', sfx='%sfx%'
)

call :fnd-nic %mac% _intf _desc _dhcp _ipv4 _ipv6 _mask _gway _dns _wins _sfx _sts "%ipconfig%"
if "%_intf%" == "" (
  if "%ipconfig%" == "" (
  	echo.  No nic with mac '%mac%' was found
  ) else (
    echo.  No nic with mac '%mac%' was found in '%ipconfig%'
  )
rem  echo.
  endlocal
  goto :eof
)

Rem Parse lists / multi-value items
if not "%ipv4%" == "" call :tokenize "%ipv4%" "|, " ipv4 1
if not "%ipv4%" == "" call :tokenize "%mask%" "|, " mask 1
if not "%ipv4%" == "" call :tokenize "%gway%" "|, " gway 1
if not "%ipv4%" == "" call :tokenize "%dns%"  "|, " dns  1
if not "%ipv4%" == "" call :tokenize "%wins%" "|, " wins 1
if not "%ipv4%" == "" call :tokenize "%sfx%"  "|, " sfx  1

rem Write commands to configure network
if not "!ipv41!" == "" echo>>"%staticip%" netsh interface ipv4 set address name="!_intf!" source=static addr=!ipv41! mask=!mask1! gateway=!gway1! gwmetric=1
if not "!ipv42!" == "" echo>>"%staticip%" netsh interface ipv4 add address name="!_intf!" addr=!ipv42! mask=!mask2! gateway=!gway2! gwmetric=1
if not "!ipv43!" == "" echo>>"%staticip%" netsh interface ipv4 add address name="!_intf!" addr=!ipv43! mask=!mask3! gateway=!gway3! gwmetric=1
if not "!dns1!"  == "" echo>>"%staticip%" netsh interface ipv4 set dnsserver name="!_intf!" source=static addr=!dns1!
if not "!dns2!"  == "" echo>>"%staticip%" netsh interface ipv4 add dnsserver name="!_intf!" addr=!dns2! index=2
if not "!dns3!"  == "" echo>>"%staticip%" netsh interface ipv4 add dnsserver name="!_intf!" addr=!dns3! index=3
if not "!wins1!" == "" echo>>"%staticip%" netsh interface ipv4 set winsserver name="!_intf!" source=static addr=!wins1!
if not "!wins2!" == "" echo>>"%staticip%" netsh interface ipv4 add winsserver name="!_intf!" addr=!wins2! index=2
if not "!wins3!" == "" echo>>"%staticip%" netsh interface ipv4 add winsserver name="!_intf!" addr=!wins3! index=3
rem if not "!sfx1!"  == "" echo>>"%staticip%" reg add "HKLM\system\currentcontrolset\services\tcpip\parameters" /v "NV Domain" /d "!sfx1!" /f
if not "!sfx1!"  == "" echo>>"%staticip%" reg add "HKLM\system\currentcontrolset\services\tcpip\parameters" /v "DHCPDomain" /d "!sfx1!" /f
if not "!sfx!"   == "!sfx1!" echo>>"%staticip%" reg add "HKLM\system\currentcontrolset\services\tcpip\parameters" /v "SearchList" /d "!sfx!" /f

if "%n%" == "1" (
  echo.  Configure '!_intf!' with IP !ipv4!
) else (
  echo.  Configure '!_intf!'[%n%] with IP !ipv4!
)
rem echo.  mac=%mac%
rem echo.  intf='!_intf!'
rem echo.  desc='!_desc!'
rem echo.  dhcp='!_dhcp!/%dhcp%'
rem echo.  ipv4='!_ipv4!/%ipv4%'
rem echo.  ipv6='!_ipv6!'
rem echo.  mask='!_mask!/%mask%'
rem echo.  gway='!_gway!/%gway%'
rem echo.  dns='!_dns!/%dns%'
rem echo.  wins='!_wins!/%wins%'
rem echo.  sfx='!_sfx!/%sfx%'
rem echo.  sts='!_sts!'
rem echo.

endlocal
goto :eof


REM ==============================================================
REM net-validate=Validate the network connection - check for IP address
REM	1 = ip check timeout
REM	2 = ip check timeout increment
REM	3 = ip check retries
REM	"4" = ips to exclude(-) / include(+)
REM	return = 0 if successful
REM --------------------------------------------------------------
:net-validate
setlocal EnableDelayedExpansion EnableExtensions
echo Validating network connection (validation criteria = %~4)...
set /a timeout=%1

:net-loop
"%systemdrive%\loginw" -p %~4 -w %timeout%
rem if "%errorlevel%" == "0" goto net-ok
if %errorlevel% equ 0 goto net-ok

set /a timeout=timeout+%2
set /a x=x+1
if %x% geq %3 goto net-fail
echo.  Restarting DHCP client service: retry %x%...
net stop dhcp >nul
net start dhcp >nul
goto net-loop

:net-ok
endlocal
exit /b 0
goto :eof

:net-fail
echo.  Could not aquire IP address.
endlocal
exit /b 1
goto :eof


REM ==============================================================
REM authenticate=Authenticate to the network
REM	1 = authentication timeout
REM	"2" = password filename - $PwlFileTitle$
REM	"3" = computer name - $ComputerName$
REM	"4" = domain or server name - $DomainOrServer$
REM	return = 0 if successful
REM --------------------------------------------------------------
:authenticate
setlocal EnableDelayedExpansion EnableExtensions
echo Authenticating network connection...
"%systemdrive%\loginw" -f %2 -c %3 -d %4 -t %1
rem if not "%errorlevel%" == "0" goto auth-fail
if %errorlevel% neq 0 goto auth-fail

:auth-ok
endlocal
exit /b 0
goto :eof

:auth-fail
echo.  Could not authenticate network connection.
endlocal
exit /b 1
goto :eof


REM ==============================================================
REM drvload=Call drvload on every matching driver file
REM	"1" = the path to the drvload.lst file to search for
REM	"2" = the path to the oem*.inf files to process
REM	return = nothing
REM --------------------------------------------------------------
:drvload
setlocal EnableDelayedExpansion EnableExtensions

set lst=%systemdrive%\drvload.lst& if not "%~1" == "" set lst=%~1
set log=%systemdrive%\drvload.log& if not "%~1" == "" set log=%~dpn1.log
set pth=%systemroot%\inf&          if not "%~2" == "" set pth=%~2
if defined pth if "%pth:~-1%" == "\" set pth=%pth:~0,-1%

if exist "%log%" del /f /q "%log%"

rem If the drvload.lst file exists, only process the files it lists
if exist "%lst%" (
  %__dbg% echo Loading drvload.lst...
  echo Loading drivers...
  for /f "usebackq tokens=1,2,3* delims=|" %%i in (`type ^"%lst%^"`) do (
    set drv=%%i& if "%%~zi" == ""   set drv=%pth%\%%i
    set msg=%%i& if not "%%j" == "" set msg=%%j ^(%%i^)
    echo.  Loading !msg!...
    dir . >nul 2>nul
    rem Only call drvload for files that exist
    if exist "!drv!" (
      drvload "!drv!" >> "%log%" 2>&1
      if errorlevel 1 echo:    Error %errorlevel% calling drvload for !msg! - ^(See %log%^)
    ) else (
      echo:    Driver file not found for !msg!
    )
  )
  endlocal
  goto :eof
)

%__dbg% echo Scanning for oem*.inf...
for %%i in ("%pth%\oem*.inf") do (
  set a=%%~ni
  set a=!a:~3!
  if !a! gtr !n! set n=!a!
)
%__dbg% echo The highest oem*.inf file is "%pth%\oem%%i.inf"

if exist "%pth%\oem*.inf" (
  echo Loading drivers...
)
for /l %%i in (0,1,%n%) do if exist "%pth%\oem%%i.inf" (
  echo.  Loading %pth%\oem%%i.inf...
  drvload "%pth%\oem%%i.inf" >> "%log%" 2>&1
  if errorlevel 1 echo:    Error %errorlevel% calling drvload for oem%%i.inf - ^(See %log%^)
)

endlocal
goto :eof


REM ==============================================================
REM fnd-pxe=Set environment variables to PXE settings
REM	1 = env variable to place the PXE server ip into (defaults to ALTIRIS_PXE_IP)
REM	2 = env variable to place the PXE server name into (defaults to ALTIRIS_PXE_SERVER)
REM	3 = env variable to place the PXE boot path into (defaults to ALTIRIS_PXE_BOOTPATH)
REM	4 = env variable to place the PXE boot menu option ID into (defaults to ALTIRIS_PXE_ID)
REM	5 = env variable to place the PXE boot menu option original ID into (defaults to ALTIRIS_PXE_OID)
REM	6 = env variable to place the PXE boot menu option redirected ID into (defaults to ALTIRIS_PXE_RID)
REM	7 = env variable to place the PXE client mac address into (defaults to ALTIRIS_PXE_CLIENTMAC)
REM	8 = env variable to place the PXE client boot nic into (defaults to ALTIRIS_PXE_INTERFACE)
REM	9 = don't validate contents (defaults to "" to validate - any other value to skip)
REM	"10"... = additional parameters to pass to getpxe utility
REM	echo = define "echo" before call to enable debug echo commands
REM	debug = define "debug" before call, to turn debug command echo on
REM	return = sets env variables to PXE settings
REM   Examples:
REM	call fnd-pxe ALTIRIS_PXE_IP ALTIRIS_PXE_SERVER ALTIRIS_PXE_BOOTPATH ALTIRIS_PXE_ID ALTIRIS_PXE_OID ALTIRIS_PXE_RID ALTIRIS_PXE_CLIENTMAC ALTIRIS_PXE_INTERFACE
REM	call fnd-pxe ALTIRIS_PXE_IP ALTIRIS_PXE_SERVER ALTIRIS_PXE_BOOTPATH ALTIRIS_PXE_ID ALTIRIS_PXE_OID ALTIRIS_PXE_RID ALTIRIS_PXE_CLIENTMAC ALTIRIS_PXE_INTERFACE novalidate
REM --------------------------------------------------------------
:fnd-pxe
setlocal EnableDelayedExpansion EnableExtensions

set epxe_ip=%~1
set epxe_server=%~2
set epxe_bootpath=%~3
set epxe_id=%~4
set epxe_oid=%~5
set epxe_rid=%~6
set epxe_mac=%~7
set epxe_nic=%~8
set novalidate=%~9
shift & shift & shift & shift & shift & shift & shift & shift & shift & shift
set p=%0 %1 %2 %3 %4 %5 %6 %7 %8 %9 

if "%epxe_ip%" == ""       set epxe_ip=ALTIRIS_PXE_IP
if "%epxe_server%" == ""   set epxe_server=ALTIRIS_PXE_SERVER
if "%epxe_bootpath%" == "" set epxe_bootpath=ALTIRIS_PXE_BOOTPATH
if "%epxe_id%" == ""       set epxe_ip=ALTIRIS_PXE_ID
if "%epxe_oid%" == ""      set epxe_oip=ALTIRIS_PXE_OID
if "%epxe_rid%" == ""      set epxe_rip=ALTIRIS_PXE_RID
if "%epxe_mac%" == ""      set epxe_mac=ALTIRIS_PXE_CLIENTMAC
if "%epxe_nic%" == ""      set epxe_nic=ALTIRIS_PXE_INTERFACE

if not exist "%systemdrive%\getpxe.*" goto fnd-pxe-done

set opt=
call :is-winpe3
if not errorlevel 1 set opt=/winpe2

for /f "usebackq tokens=*" %%a in (`^"%systemdrive%\getpxe^" %opt% /i %p%`)    do set pxeip=%%a
for /f "usebackq tokens=*" %%a in (`^"%systemdrive%\getpxe^" %opt% /n %p%`)    do set pxename=%%a
for /f "usebackq tokens=*" %%a in (`^"%systemdrive%\getpxe^" %opt% /p %p%`)    do set pxepath=%%a
for /f "usebackq tokens=*" %%a in (`^"%systemdrive%\getpxe^" %opt% /id:o %p%`) do set pxeoid=%%a
for /f "usebackq tokens=*" %%a in (`^"%systemdrive%\getpxe^" %opt% /id:r %p%`) do set pxerid=%%a
for /f "usebackq tokens=*" %%a in (`^"%systemdrive%\getpxe^" %opt% /m %p%`)    do set pxemac=%%a
for /f "usebackq tokens=*" %%a in (`^"%systemdrive%\getpxe^" %opt% /m:- %p%`)  do set pxemac_=%%a

rem set pxenic=
call :fnd-nic %pxemac_% pxenic

%__dbg% echo PXE server IP="%pxeip%"
%__dbg% echo PXE server name="%pxename%"
%__dbg% echo PXE boot path="%pxepath%"
%__dbg% echo PXE boot ID="%pxeid%"
%__dbg% echo PXE boot original ID="%pxeoid%"
%__dbg% echo PXE boot redirected ID="%pxerid%"
%__dbg% echo PXE client MAC="%pxemac%" (%pxemac_%)
%__dbg% echo PXE client nic="%pxenic%"

if "%novalidate%" == "" (
  for %%i in (pxeip pxename pxepath pxeid pxeoid pxerid pxemac pxenic) do (
    if "!%%i:~0,2!" == "**" set %%i=
    if "!%%i:~0,2!" == "$$" set %%i=
  )
)

rem Set PXE_ID to either redirected ID or original ID
if not defined pxeid set pxeid=%pxerid%
if not defined pxeid set pxeid=%pxeoid%

:fnd-pxe-done
endlocal & set %epxe_ip%=%pxeip%& set %epxe_server%=%pxename%& set %epxe_bootpath%=%pxepath%& set %epxe_id%=%pxeid%& set %epxe_oid%=%pxeoid%& set %epxe_rid%=%pxerid%& set %epxe_mac%=%pxemac%& set %epxe_mac%_=%pxemac_%& set %epxe_nic%=%pxenic%
goto :eof


REM ==============================================================
REM fnd-nic=Find nic adapter interface (and settings) for a MAC address
REM	1  = MAC address to search for
REM	2  = env variable to place the nic interface name into (defaults to ALTIRIS_NIC_INTERFACE)
REM	3  = env variable to place the nic description into (defaults to ALTIRIS_NIC_DESCRIPTION)
REM	4  = env variable to place the nic dhcp setting into (defaults to ALTIRIS_NIC_DHCP) (true/false/"")
REM	5  = env variable to place the nic ipv4 address into (defaults to ALTIRIS_NIC_IPADDR)
REM	6  = env variable to place the nic ipv6 address into (defaults to ALTIRIS_NIC_IPV6ADDR)
REM	7  = env variable to place the nic net mask into (defaults to ALTIRIS_NIC_NETMASK)
REM	8  = env variable to place the nic gateway into (defaults to ALTIRIS_NIC_GATEWAY)
REM	9  = env variable to place the nic dns servers into (defaults to ALTIRIS_NIC_DNS)
REM	10 = env variable to place the nic wins servers into (defaults to ALTIRIS_NIC_WINS)
REM	11 = env variable to place the nic dns suffix into (defaults to ALTIRIS_NIC_SFX)
REM	12 = env variable to place the nic status into (defaults to ALTIRIS_NIC_STATUS) (true/false/"")
REM	13 = name of file to read ipconfig data from (defaults to "", which means run ipconfig/all)
REM	return = sets env variable to interface name
REM --------------------------------------------------------------
:fnd-nic
setlocal EnableDelayedExpansion EnableExtensions

set fndmac=%~1&   shift & set fndmac=!fndmac: =!& set fndmac=!fndmac:-=!& set fndmac=!fndmac::=!
set enicintf=%~1& shift & if "!enicintf!" == "" set enicintf=ALTIRIS_NIC_INTERFACE
set enicdesc=%~1& shift & if "!enicdesc!" == "" set enicdesc=ALTIRIS_NIC_DESCRIPTION
set enicdhcp=%~1& shift & if "!enicdhcp!" == "" set enicdhcp=ALTIRIS_NIC_DHCP
set enicipv4=%~1& shift & if "!enicipv4!" == "" set enicipv4=ALTIRIS_NIC_IPADDR
set enicipv6=%~1& shift & if "!enicipv6!" == "" set enicipv6=ALTIRIS_NIC_IPV6ADDR
set enicmask=%~1& shift & if "!enicmask!" == "" set enicmask=ALTIRIS_NIC_NETMASK
set enicgway=%~1& shift & if "!enicgway!" == "" set enicgway=ALTIRIS_NIC_GATEWAY
set enicdns=%~1&  shift & if "!enicdns!"  == "" set enicdns=ALTIRIS_NIC_DNS
set enicwins=%~1& shift & if "!enicwins!" == "" set enicwins=ALTIRIS_NIC_WINS
set enicsfx=%~1&  shift & if "!enicsfx!"  == "" set enicsfx=ALTIRIS_NIC_SFX
set enicsts=%~1&  shift & if "!enicsts!"  == "" set enicsts=ALTIRIS_NIC_STATUS
set ipconfig=%~1& shift
set multi=true
set _cmd_=ipconfig /all
if defined ipconfig set _cmd_=type %ipconfig%
rem echo Using '%_cmd_%'...

call :deleteenv "_#"
for /f "usebackq eol=; tokens=1* delims=:" %%a in (`%_cmd_%`) do (
  rem Parse item and value
  call :fnd-nic0 item %%a
  call :fnd-nic0 val "%%b"

  rem fixup untagged items
  set aa=%%a
  if "!val!" == "" if /i "!item:~0,15!" == "Ethernetadapter" set item=Ethernetadapter& call :fnd-nic0 val "%%a"
  if "!val!" == "" if not "!aa:~-3!" == " . " if /i not "!item:~0,22!" == "WindowsIPConfiguration" set val=!item!& set item=
rem echo '!item!'='!val!'

  rem Save temporary items
  if /i "!item:~0,15!" == "Ethernetadapter" call :fnd-nic1 "!item!" "!val!"

  rem Store items for later
  call :fnd-nic2 "!item!" "!val!" "!!multi!!"
)

rem Save final set of temporary items
call :fnd-nic1 "!item!" "!val!"

rem Get items for the specified mac
call :fnd-nic3 "%fndmac%"

rem %__dbg% echo Nic with mac %fndmac% is "%tmpintf%"

endlocal & set %enicintf%=%tmpintf%& set %enicdesc%=%tmpdesc%& set %enicdhcp%=%tmpdhcp%& set %enicipv4%=%tmpipv4%& set %enicipv6%=%tmpipv6%& set %enicmask%=%tmpmask%& set %enicgway%=%tmpgway%& set %enicdns%=%tmpdns%& set %enicwins%=%tmpwins%& set %enicsfx%=%tmpsfx%& set %enicsts%=%tmpsts%
goto :eof

:fnd-nic0
setlocal EnableDelayedExpansion EnableExtensions
set evar=%~1
set val=
:fnd-nic0a
if not "%~2" == "." set val=%val%%~2
shift
if not "%~2" == "" goto fnd-nic0a
if "!val:~0,1!"  == " " set val=!val:~1!
if "!val:~-1,1!" == " " set val=!val:~0,-1!
if "!val:~-1,1!" == "." set val=!val:~0,-1!
endlocal & set %evar%=%val%
goto :eof

rem Save temporary items
:fnd-nic1
if defined tmpintf (
  set tmpmac=!tmpmac: =!& set tmpmac=!tmpmac:-=!& set tmpmac=!tmpmac::=!
  set _#!tmpmac!_mac=!tmpmac!
  set _#!tmpmac!_desc=!tmpdesc!
  set _#!tmpmac!_intf=%tmpintf%
  set _#!tmpmac!_dhcp=%tmpdhcp%
  set _#!tmpmac!_ipv4=%tmpipv4%
  set _#!tmpmac!_ipv6=%tmpipv6%
  set _#!tmpmac!_mask=%tmpmask%
  set _#!tmpmac!_gway=%tmpgway%
  set _#!tmpmac!_dns=%tmpdns%
  set _#!tmpmac!_wins=%tmpwins%
  set _#!tmpmac!_sfx=%tmpsfx%
  set _#!tmpmac!_sts=%tmpsts%
  set tmpmac=
  set tmpdesc=
  set tmpintf=
  set tmpdhcp=
  set tmpipv4=
  set tmpipv6=
  set tmpmask=
  set tmpgway=
  set tmpdns=
  set tmpwins=
  set tmpsfx=
  set tmpsts=
  set lastitem=
)
goto :eof

rem Store items for later
:fnd-nic2
rem set multi=%~3
if defined multi if "!item!" == "" if defined lastitem (
  if /i "!lastitem!" == "IPAddress"             set tmpipv4=!tmpipv4!,!val!
  if /i "!lastitem!" == "IPV4Address"           set tmpipv4=!tmpipv4!,!val!
  if /i "!lastitem!" == "Link-localIPV6Address" set tmpipv6=!tmpipv6!,!val!
  if /i "!lastitem!" == "SubnetMask"            set tmpmask=!tmpmask!,!val!
  if /i "!lastitem!" == "DefaultGateway"        set tmpgway=!tmpgway!,!val!
  if /i "!lastitem!" == "DNSServers"            set tmpdns=!tmpdns!,!val!
rem  if /i "!lastitem!" == "DHCPServer"            set tmpd=!tmpd!,!val!
  if /i "!lastitem!" == "DNSSuffixSearchList"   set tmpsfx=!tmpsfx!,!val!
  goto :eof
)
if /i "!item!" == "PhysicalAddress"      set tmpmac=!val!
if /i "!item!" == "EthernetAdapter"      set tmpintf=!val!
if /i "!item!" == "Description"          set tmpdesc=!val!
if /i "!item!" == "DHCPEnabled"          set tmpdhcp=!val!
if /i "!item!" == "PrimaryWINSServer"    set tmpwins=!val!
if defined multi (
  if /i "!item!" == "SecondaryWINSServer"   set tmpwins=!tmpwins!,!val!
  if /i "!item!" == "IPAddress"             set tmpipv4=!tmpipv4!,!val!
  if /i "!item!" == "IPV4Address"           set tmpipv4=!tmpipv4!,!val!
  if /i "!item!" == "Link-localIPV6Address" set tmpipv6=!tmpipv6!,!val!
  if /i "!item!" == "SubnetMask"            set tmpmask=!tmpmask!,!val!
  if /i "!item!" == "DefaultGateway"        set tmpgway=!tmpgway!,!val!
  if /i "!item!" == "DNSServers"            set tmpdns=!tmpdns!,!val!
rem  if /i "!item!" == "DHCPServer"            set tmpd=!tmpd!,!val!
  if /i "!item!" == "DNSSuffixSearchList"   set tmpsfx=!tmpsfx!,!val!
  if /i "!item!" == "Connection-SpecificDNSSuffix" set tmpsfx=!val!
) else (
  if /i "!item!" == "SecondaryWINSServer"   set tmpwins=!val!
  if /i "!item!" == "IPAddress"             set tmpipv4=!val!
  if /i "!item!" == "IPV4Address"           set tmpipv4=!val!
  if /i "!item!" == "Link-LocalIPV6Address" set tmpipv6=!val!
  if /i "!item!" == "SubnetMask"            set tmpmask=!val!
  if /i "!item!" == "DefaultGateway"        set tmpgway=!val!
  if /i "!item!" == "DNSServers"            set tmpdns=!val!
rem  if /i "!item!" == "DHCPServer"            set tmpd=!val!
  if /i "!item!" == "DNSSuffixSearchList"   set tmpsfx=!val!
  if /i "!item!" == "Connection-SpecificDNSSuffix" set tmpsfx=!val!
)
if /i "!item!" == "MediaState"              set tmpsts=!val!
rem if /i "!item!" == "NetBIOSoverTcpip"       set tmpd=!val!
rem if /i "!item!" == "LeaseObtained"          set tmpd=!val!
rem if /i "!item!" == "LeaseExpires"           set tmpd=!val!
rem if /i "!item!" == "AutoconfigurationEnabled"     set tmpd=!val!
rem if /i "!item!" == "HostName"               set tmpd=!val!
rem if /i "!item!" == "PrimaryDnsSuffix"       set tmpd=!val!
rem if /i "!item!" == "NodeType"               set tmpd=!val!
rem if /i "!item!" == "IPRoutingEnabled"       set tmpd=!val!
rem if /i "!item!" == "WINSProxyEnabled"       set tmpd=!val!
if not "!item!" == "" set lastitem=!item!
goto :eof

rem Get items for specified mac
:fnd-nic3
set tmpmac=!_#%fndmac%_mac!
set tmpdesc=!_#%fndmac%_desc!
set tmpintf=!_#%fndmac%_intf!
set tmpdhcp=!_#%fndmac%_dhcp!
set tmpipv4=!_#%fndmac%_ipv4!
set tmpipv6=!_#%fndmac%_ipv6!
set tmpmask=!_#%fndmac%_mask!
set tmpgway=!_#%fndmac%_gway!
set tmpdns=!_#%fndmac%_dns!
set tmpwins=!_#%fndmac%_wins!
set tmpsfx=!_#%fndmac%_sfx!
set tmpsts=!_#%fndmac%_sts!
rem Cleanup values
if not "!tmpmac!" == ""    set tmpmac=!tmpmac: =!& set tmpmac=!tmpmac:-=!& set tmpmac=!tmpmac::=!
if not "!tmpintf!" == ""   set tmpintf=!tmpintf:Ethernet adapter =!
rem if not "!tmpintf!" == ""   set tmpintf=!tmpintf: :=!
if not "!tmpipv4!" == ""   set tmpipv4=!tmpipv4:(Preferred)=!
if not "!tmpipv4!" == ""   set tmpipv4=!tmpipv4:(Preferred=!
if not "!tmpipv6!" == ""   set tmpipv6=!tmpipv6:(Preferred)=!
if not "!tmpipv6!" == ""   set tmpipv6=!tmpipv6:(Preferred=!
if "!tmpipv4:~0,1!" == "," set tmpipv4=!tmpipv4:~1!
if "!tmpipv6:~0,1!" == "," set tmpipv6=!tmpipv6:~1!
if "!tmpmask:~0,1!" == "," set tmpmask=!tmpmask:~1!
if "!tmpgway:~0,1!" == "," set tmpgway=!tmpgway:~1!
if "!tmpdns:~0,1!" == ","  set tmpdns=!tmpdns:~1!
if "!tmpwins:~0,1!" == "," set tmpdns=!tmpwins:~1!
if "!tmpsfx:~0,1!" == ","  set tmpsfx=!tmpsfx:~1!
rem if "!tmpd:~0,1!" == ","   set tmpd=!tmpd:~1!
if /i "!tmpdhcp!" == "yes" set tmpdhcp=true
if /i "!tmpdhcp!" == "no"  set tmpdhcp=false
if /i "!tmpsts!" == "Media Disconnected" set tmpsts=false
if not "!tmpdhcp!" == ""   set tmpsts=true
goto :eof


REM ==============================================================
REM fnd-share=Find the Deployment Share - the last matching entry is returned
REM	1 = name of the server to search for (* = any)
REM	2 = name of the share to search for (* = any, defaults to EXPRESS)
REM	3 = env variable to set to the drive mapped to the Deployment share (defaults to ALTIRIS_SHARE)
REM	4 = env variable to set to the UNC of the Deployment share (defaults to ALTIRIS_UNC)
REM	5 = env variable to set to the server name of the Deployment share (defaults to ALTIRIS_DS_SERVER)
REM	6 = env variable to set to the share name of the Deployment share (defaults to ALTIRIS_DS_SHARE)
REM	7 = default drive letter to use if no mapping can be found (including ":")
REM	8 = default UNC to use if no mapping can be found
REM	9 = default server to use if no mapping can be found
REM	10 = default share to use if no mapping can be found
REM	11 = non-blank to use the first matching entry instead of the last (not used now)
REM	return = sets env variables to drive and UNC of the Deployment Share (last matching entry)
REM --------------------------------------------------------------
:fnd-share
setlocal EnableDelayedExpansion EnableExtensions

set server=%~1
if "%server%" == "" set server=DS
set share=%~2
if "%share%" == "" set share=express
set edrv=%~3
if "%edrv%" == "" set edrv=ALTIRIS_SHARE
set eunc=%~4
if "%eunc%" == "" set eunc=ALTIRIS_UNC
set esrv=%~5
if "%esrv%" == "" set esrv=ALTIRIS_DS_SERVER
set eshr=%~6
if "%eshr%" == "" set eshr=ALTIRIS_DS_SHARE
shift & shift & shift & shift & shift & shift

%__dbg% echo Searching for a drive mapped to "\\%server%\%share%"
rem %__dbg% for /f "tokens=1,2,3* usebackq eol=-" %%i in (`net use`) do echo Map data: sts="%%i", drv="%%j", unc="%%k"

for /f "tokens=1,2,3* usebackq eol=-" %%i in (`net use`) do call :cmp-share "%server%" "%share%" %%i %%j "%%k" tdrv tunc tsrv tshr "%~5"
if "%tdrv%" == "" set tdrv=%~1
if "%tunc%" == "" set tunc=%~2
if "%tsrv%" == "" set tsrv=%~3
if "%tshr%" == "" set tshr=%~4

endlocal& set %edrv%=%tdrv%& set %eunc%=%tunc%& set %esrv%=%tsrv%& set %eshr%=%tshr%
goto :eof

:cmp-share
rem 1 = server to look for
rem 2 = share to look for
rem 3 = status of the mapped drive (OK, Disconnected, etc)
rem 4 = drive letter of the mapped drive (must include ":")
rem 5 = unc of the mapped drive
rem 6 = env var for the drive letter
rem 7 = env var for the unc
rem 8 = env var for the server name
rem 9 = env var for the share name
rem 10 = flag to use first drive not last
setlocal EnableDelayedExpansion EnableExtensions

set server=%~1
set share=%~2
rem if /i not "%~3" == "OK" goto :eof
set drv=%~4
if "%drv%" == "" goto :eof
if not "%drv:~-1%" == ":" goto :eof
set unc=%~5
if "%unc%" == "" goto :eof
if not "%unc:~0,2%" == "\\" goto :eof

for /f "usebackq tokens=1,2* delims=\" %%i in (`echo %unc%`) do (set tsrv=%%i&set tshr=%%j)
%__dbg% echo.  Drive %drv% is connected to "%unc%" ("%tsrv%", "%tshr%")

if not "%server%" == "*" (
  if not "%share%" == "*" (
    if /i not "%unc%" == "\\%server%\%share%" goto :eof
  ) else (
    if /i not "%tsrv%" == "%server%" goto :eof
  )
) else (
  if not "%share%" == "*" (
    if /i not "%tshr%" == "%share%" goto :eof
  )
)
%__dbg% echo *Found mapping at drive %drv%

endlocal& set %~6=%drv%& set %~7=%unc%& set %~8=%tsrv%& set %~9=%tshr%
goto :eof


REM ==============================================================
REM set-temp=Set "temp" folder
REM	"1" = path to folder to use as temp folder
REM	"2" = path to use if temp folder not found
REM	"3" = env variable to set (defaults to "temp")
REM	return = temp folder returned in "temp" variable
REM --------------------------------------------------------------
:set-temp
setlocal

set etmp=temp& if not "%~3" == "" set etmp=%~3
set t=~t%random%~

rem First try the current tmp environment variable
if defined tmp if exist "%tmp%" (
  md "%tmp%\%t%" 1>nul 2>nul
  if not errorlevel 1 (
    rd "%tmp%\%t%"
    set vtmp=%tmp%
    goto temp-done
  )
)
%__dbg% echo Local tmp path not valid.

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

rem Now try the specified path
rem cd "%vtmp%\" >nul 2>nul
rem if not ERRORLEVEL 1 goto temp-done
if exist "%vtmp%" (
  md "%vtmp%\%t%" 1>nul 2>nul
  if not errorlevel 1 (
    rd "%vtmp%\%t%"
    goto temp-done
  )
)
%__dbg% echo Specified path '%~1' not valid.

rem Try the default location
set vtmp=
if "%~2" == "" goto temp-done
if "%~2" == ":" goto temp-done
%__dbg% echo Trying default path '%~2'.

rem Create a client unique temporary folder on the share
"%systemdrive%\loginw" -i
set ip=%errorlevel%
rem	set ip=12345
%__dbg% echo ip="%ip%"
if "%ip:~0,1%" == "-" set ip=%ip:~1%
set vtmp=%~2\temp\t%ip%
%__dbg% echo vtmp="%vtmp%"

md "%vtmp%\" 2>nul
rd /s /q "%vtmp%\" 2>nul
md "%vtmp%\" 2>nul

:temp-done
%__dbg% echo vtmp="%vtmp%"
endlocal & set %etmp%=%vtmp%
goto :eof


REM ==============================================================
REM fnd-bootdisk=Find the disk drive where the pre-boot environment booted from
REM	1 = flag file to search for on boot device (defaults to atrsboot)
REM	2 = env variable to define to boot device (defaults to ALTIRIS_BOOTDISK)
REM	3 = The boot device type (usually stored in ALTIRIS_BOOTDEVICE)
REM	4 = default value to use if no drive was found (including ":")
REM	return = sets env variable to disk drive where file is found (including ":")
REM --------------------------------------------------------------
REM The original boot disk will contain a file called atrsboot.
REM If we find the disk drive containing that file, then this is the disk we booted from.
:fnd-bootdisk
setlocal EnableDelayedExpansion EnableExtensions
set evar=ALTIRIS_BOOTDISK&    if not "%~2" == "" set evar=%~2
set dev=%ALTIRIS_BOOTDEVICE%& if not "%~3" == "" set dev=%~3
set dsk=%systemdrive%&        if not "%~4" == "" set dsk=%~4

call :is-boot-pxe
if not errorlevel 1 goto bootdisk-done
echo Locating boot drive...
set %evar%=
set dsk=

set /a n=0
:fnd-bootdisk2
rem First see if there is a registry key for this item
call :regkey-read HKLM\System\CurrentControlSet\Control PEBootRamdiskSourceDrive dsk
if defined dsk echo.  Found boot drive %dsk% in registry:CurrentControlSet.
if defined dsk goto bootdisk-done
call :regkey-read HKLM\System\ControlSet001\Control PEBootRamdiskSourceDrive dsk
if defined dsk echo.  Found boot drive %dsk% in registry:ControlSet001.
if defined dsk goto bootdisk-done

rem Attempt to initialize WinPE in order to set up the above registry key
rem if /i not "%dev:~0,5%" == "cdrom" if exist "%systemroot%\system32\wpeutil.*" if %x% lss 15 (
call :is-boot-cdrom-dvd
if errorlevel 1 if exist "%systemroot%\system32\wpeutil.*" if %n% lss 10 (
  set /a n=n + 1
  set /a m=n %% 3
  if !m! equ 0 (
    set /a r=r + 1
    echo.  Waiting for boot drive to initialize: retry !r!...
  )
  %systemdrive%\await 1
  wpeutil UpdateBootInfo >nul
  goto fnd-bootdisk2
)
%__dbg% echo.  Unable to locate boot disk in registry.

rem Try the autoutil utility
if exist "%systemdrive%\autoutil.*" (
  set idx=
  "%systemdrive%\autoutil" -b %dev% >nul 2>nul
  if !errorlevel! geq 11 if !errorlevel! leq 36 set /a idx=!errorlevel!-11
  if defined idx (
    set dsks=ABCDEFGHIJKLMNOPQRSTUVWXYZ
    set dsk=!dsks:~%idx%,1!:
    call :is-boot-dir
    if not errorlevel 1 set dsk=!dsk!\boot\altiris\iso
    echo.  Found boot drive %dsk% using autoutil.
    goto bootdisk-done
  )
)
if defined dsk echo.  Found boot drive %dsk% using autoutil.
if defined dsk goto bootdisk-done

rem Search for the flag file
if "%~1" == "" ( call :fnd-bootdisk atrsboot dsk "%dev%" "%~4" & goto bootdisk-done )
set dsks=c:\;d:\;e:\;f:\;g:\;h:\;i:\;j:\;k:\;l:\;m:\;n:\;o:\;p:\;q:\;r:\;s:\;t:\;u:\;v:\;w:\;x:\;y:\;z:\
set dsk=%~d$dsks:1
if defined dsk echo.  Found boot drive %dsk%\%~1.
if defined dsk goto bootdisk-done

set b=boot
set dsks=c:\%b%;d:\%b%;e:\%b%;f:\%b%;g:\%b%;h:\%b%;i:\%b%;j:\%b%;k:\%b%;l:\%b%;m:\%b%;n:\%b%;o:\%b%;p:\%b%;q:\%b%;r:\%b%;s:\%b%;t:\%b%;u:\%b%;v:\%b%;w:\%b%;x:\%b%;y:\%b%;z:\%b%
set dsk=%~d$dsks:1
if defined dsk echo.  Found boot drive %dsk%\%b%\%~1.
if defined dsk goto bootdisk-done

rem Use default value
set dsk=%~4
echo.  Unable to determine boot disk - using %~4.

:bootdisk-done
if "%dsk:~-1%" == "\" set dsk=%dsk:~0,-1%
call :is-boot-dir
if not errorlevel 1 set dsk=%dsk%\boot\altiris\iso
endlocal & set %evar%=%dsk%
goto :eof


REM ==============================================================
REM fnd-aclient=Find highest version of the aclient
REM	1 = env variable to return the file name in (defaults to aclient)
REM	2 = Blank to run remote agent - $RunRemoteAgent$
REM	3 = processor type (defaults to x86)
REM	4 = path to search for aclient (defaults to .)
REM	5 = default path if not found (defauls to aclient.exe)
REM	6 = Non-blank to display name of aclient being examined
REM	return = highest file name returned in env variable
REM --------------------------------------------------------------
:fnd-aclient
setlocal EnableDelayedExpansion EnableExtensions
set /a v=0
set efil=aclient& if not "%~1" == "" set efil=%~1
set prc=x86& if not "%3" == "" set prc=%3
set pth=.&   if not "%~4" == "" set pth=%~4
set def=aclient.exe& if not "%~5" == "" set def=%~5
if "%~2" == "" goto rmt-aclient
endlocal & set %efil%=%def%
goto :eof

:rmt-aclient
for /f "usebackq tokens=3,4,5,6 delims=-." %%i in (`dir /b /a-d /one ^"%pth%\altiris-aclient-*.*.*.%prc%.exe^" 2^>nul`) do call :cmp-aclient %%i %%j %%k "%pth%\altiris-aclient-%%i.%%j.%%k.%prc%.exe" %~6
if "%aclient%" == "" set aclient=%def%
endlocal & set %efil%=%aclient%
goto :eof

:cmp-aclient
setlocal EnableDelayedExpansion EnableExtensions
set /a t=(1%1 * 10000000) + (1%2 * 10000) + (1%3)
if not "%~5" == "" echo.  ^> %t% .. %4
rem if %t% gtr %v% set aclient=%~fs4& set /a v=t
if %t% gtr %v% set aclient=%~f4& set /a v=t
endlocal & set v=%v%& set aclient=%aclient%
goto :eof


REM ==============================================================
REM fnd-file=Find highest version of a file
REM	1 = env variable to return the file name in (defaults to file)
REM	2 = env variable to return the version in (defaults to ver)
REM	3 = wildcard of file to find (required)
REM	4 = path to search for agent (defaults to .)
REM	5 = Non-blank to display name of agent being examined
REM	return = highest file name returned in env variable
REM		 highest version returned in "ver"
REM --------------------------------------------------------------
:fnd-file
setlocal EnableDelayedExpansion EnableExtensions
set efil=file& if not "%~1" == "" set efil=%~1
set ever=ver&  if not "%~2" == "" set ever=%~2
set nam=%~3
set pth=.&     if not "%~4" == "" set pth=%~f4
rem echo pth=%pth%\%nam%
set /a v=0
for /f "usebackq tokens=3,4,5,6 delims=-." %%i in (`dir /b /a-d /one ^"%pth%\%nam%^" 2^>nul`) do call :cmp-file %%i %%j %%k "%pth%\%nam%" %~5
if not "%~5" == "" if defined ver (
  echo.  ^> Highest ver=%ver%
  echo.  ^> Highest file=%file%
)
endlocal & set %efil%=%file%& set %ever%=%ver%
goto :eof

:cmp-file
set /a t=(1%1 * 10000000) + (1%2 * 10000) + (1%3)
rem if not "%~5" == "" echo.  ^> %t% .. %4
if not "%~5" == "" echo.  ^> %1.%2.%3 .. %4
if %t% gtr %v% (
  for /f "tokens=1* delims=*" %%i in ("%~4") do set file=%%i%1.%2.%3%%j
  set ver=%1.%2.%3
  set /a v=t
)
goto :eof


REM ==============================================================
REM filepart=Get part of a file path
REM	"1" = the path to extract the part from
REM	"2" = the part of the path to extract (default=dp)
REM	"3" = the environment variable to return the result in (default=part)
REM	return = the part of the path is returned in the env variable
REM --------------------------------------------------------------
:filepart
setlocal EnableDelayedExpansion EnableExtensions

set evar=part& if not "%~3" == "" set evar=%~3

if /i "%~2" == "f"  set _t=%~f1
if /i "%~2" == "s"  set _t=%~s1
if /i "%~2" == "d"  set _t=%~d1
if /i "%~2" == "p"  set _t=%~p1
if /i "%~2" == "n"  set _t=%~n1
if /i "%~2" == "x"  set _t=%~x1
if /i "%~2" == "dp" set _t=%~dp1
if /i "%~2" == "nx" set _t=%~nx1

endlocal & set %evar%=%_t%
goto :eof


REM ==============================================================
REM regkey-load=Load registry settings from files
REM	"1" = the path to the reg files to load
REM	return = nothing
REM --------------------------------------------------------------
:regkey-load
setlocal EnableDelayedExpansion EnableExtensions

set fil=%systemdrive%\regkey.lst& if not "%~1" == "" set fil=%~1
if exist "%fil%" echo Loading registry settings...
for %%i in (^"%fil%^") do echo.  Loading %%~nxi... & call :regkey-file "%%i"

endlocal
goto :eof

:regkey-file
setlocal EnableDelayedExpansion EnableExtensions

set ext=%~x1
if /i "%ext%" == ".reg" (
  regedit /s "%~1"
)
if /i "%ext%" == ".lst" (
  for /f "usebackq tokens=1,2* delims=|" %%i in (`type ^"%~1^"`) do call :regkey-write "%%i" "%%j" "%%k"
)

endlocal
goto :eof


REM ==============================================================
REM regkey-read=Get the value of a registry item
REM	"1" = registry key for item to obtain
REM	"2" = registry item to get value of
REM	3   = env variable to place the value into (defaults to "_%2_")
REM	"4" = default value if item not found (defaults to "")
REM	return = sets env variable in %3 to value of registry item
REM --------------------------------------------------------------
:regkey-read
setlocal EnableDelayedExpansion EnableExtensions

set evar=%~3
rem if "%evar%" == "" set evar=REG_KEY
if "%evar%" == "" set evar=_%~2_
rem set evar=%evar: =%

set val=%~4
if "%~1" == "" goto regkey-read-done
if "%~2" == "" goto regkey-read-done

rem set fnd=findstr
set fnd=find

%__dbg% reg query "%~1" /v "%~2"
%__dbg% reg query "%~1" /v "%~2" | %fnd% /i "REG_"
rem pause

for /f "usebackq eol=! tokens=2* delims=	 " %%a in (`reg query ^"%~1^" /v ^"%~2^" 2^>nul ^| %fnd% /i ^"REG_^"`) do set val=%%b
if "%val%" == "" (set ret=1) else (set ret=0)
if "%val%" == "" set val=%~4

:regkey-read-done
endlocal & set %evar%=%val%& exit /b %ret%
goto :eof


REM ==============================================================
REM regkey-write=Write the value of a registry item
REM	"1" = registry key for item to write
REM	"2" = registry item to write value to
REM	"3" = value to write to registry key ("" to delete item)
REM	"4" = data type for registry key (defaults to "REG_SZ")
REM	return = 
REM --------------------------------------------------------------
:regkey-write
setlocal EnableDelayedExpansion EnableExtensions

if "%~1" == "" goto regkey-write-done
if "%~2" == "" goto regkey-write-done
set type=%~4
if "%type%" == "" set type=REG_SZ

if not "%~3" == "" (
rem  echo Adding registry item "%~1\%~2=%~3"...
  reg add "%~1" /v "%~2" /d "%~3" /t %type% /f >nul
) else (
rem  echo Deleting registry item "%~1\%~2"...
  reg delete "%~1" /v "%~2" /f >nul
)

:regkey-write-done
endlocal
goto :eof


REM ==============================================================
REM ini-read=Get the value of an ini file item
REM	"1" = ini file to read item from
REM	"2" = ini section for item to obtain
REM	"3" = ini item to get value of ("" to read all items in section)
REM	4   = env variable to place the value into (defaults to "_%3_")
REM	"5" = default value if item not found (defaults to "")
REM	"6" = env variable to place the keys into (defaults to ignore)
REM	return = sets env variable in %4 to value of ini item
REM --------------------------------------------------------------
:ini-read
setlocal EnableDelayedExpansion EnableExtensions
if "%~2" == "" goto ini-read-done

set eval=%~4& if "!eval!" == "" set eval=_%~3_
set val=%~5
set ekey=%~6& if "!ekey!" == "" set ekey=~~tmp~~

if "%~3" == "" (
  %__dbg% echo Reading ini section "%~1:[%~2]"...
  if "%~6" == "" (
    for /f "usebackq eol=; tokens=1* delims==" %%a in (`iniuser /q "%~1" get "%~2"`) do if not "%%a" == "" set val=!val!,%%a
  ) else (
    for /f "usebackq eol=; tokens=1,2* delims==" %%a in (`iniuser /q /k "%~1" get "%~2"`) do if not "%%a" == ""  set val=!val!,%%b& set key=!key!,%%a
  )
) else (
  %__dbg% echo Reading ini item "%~1:[%~2]%~3"...
  for /f "usebackq eol=; tokens=1* delims==" %%a in (`iniuser /q "%~1" get "%~2" "%~3"`) do set val=%%a
)
if "%val%" == "" (set ret=1) else (set ret=0)
if "%val%" == "" (
  set val=%~5
) else if "%val:~0,1%" == "," (
  set val=%val:~1%
)

endlocal & set %eval%=%val%& set %ekey%=%key%& exit /b %ret%
:ini-read-done
goto :eof


REM ==============================================================
REM ini-write=Write the value of an ini file item
REM	"1" = ini file to write item to
REM	"2" = ini section for item to write
REM	"3" = ini item to write value to ("" to delete section)
REM	"4" = value to write to ini item ("" to delete item)
REM	return = 
REM --------------------------------------------------------------
:ini-write
setlocal EnableDelayedExpansion EnableExtensions
if "%~2" == "" goto ini-write-done

if "%~3" == "" (
  %__dbg% echo Deleting ini section "%~1:[%~2]"...
  iniuser /q "%~1" delete "%~2" >nul
) else if "%~4" == "" (
  %__dbg% echo Deleting ini item "%~1:[%~2]%~3"...
  iniuser /q "%~1" delete "%~2" "%~3" >nul
) else (
  %__dbg% echo Adding ini item "%~1:[%~2]%~3=%~4"...
  iniuser /q "%~1" set "%~2" "%~3" "%~4" >nul
)

endlocal
:ini-write-done
goto :eof

