@echo off
set BackupDrive=D:
set ImagePath=Latest.wim
set EF="%CD%\exclude.ini"

chcp 1251 >nul
echo [ExclusionList] >%EF%

pushd "%BackupDrive%\"
if NOT %ERRORLEVEL%==0 goto BackupFailed
for /F "usebackq delims=" %%i in (`dir /AD /B /L`) do if "%%i"=="users" call :ProcessUsers "%%i" 2>nul
popd

imagex /norpfix /config exclude.ini /capture %BackupDrive%\ %ImagePath% "System Image"
goto :eof

:ProcessUsers
  pushd %1
  if NOT %ERRORLEVEL%==0 goto CleanupFailed
  for /F "usebackq delims=" %%i in (`dir /AD /B /L`) do call :ProcessUserEntry "%%i" 2>nul
  popd
goto :eof

:ProcessUserEntry
  if %1=="all users" goto :eof
  if %1=="default" goto :eof
  if %1=="default user" goto :eof
  if %1=="desktop.ini" goto :eof
  if %1=="все пользователи" goto :eof
  
  call :ProcessHomeFolder %1
goto :eof

:ProcessHomeFolder
  pushd %1
  call :AddException "AppData\Local\VirtualStore"
  call :AddException "AppData\Local\Microsoft\Outlook"
  if NOT %ERRORLEVEL%==0 goto CleanupFailed
  for /F "usebackq delims=" %%i in (`dir /B /L`) do call :ProcessUserFileOrFolder "%%i" 2>nul
  popd
goto :eof

:ProcessUserFileOrFolder
  echo %1 | find "ntuser." >nul && goto :eof 
  if %1=="appdata" goto :eof
  if %1=="application data" goto :eof
  if %1=="program files" goto :eof
  if %1=="cookies" goto :eof
  if %1=="local settings" goto :eof
  if %1=="my documents" goto :eof
  if %1=="мои документы" goto :eof
  if %1=="nethood" goto :eof
  if %1=="printhood" goto :eof
  if %1=="recent" goto :eof
  if %1=="sendto" goto :eof
  if %1=="start menu" goto :eof
  if %1=="главное меню" goto :eof
  if %1=="templates" goto :eof
  if %1=="шаблоны" goto :eof
  if %1=="desktop.ini" goto :eof
  if %1=="memory max" (call :AddException %1 && goto :eof)

  pushd %1
  if NOT %ERRORLEVEL%==0 (call :AddException %1 && goto :eof)
  for /F "usebackq delims=" %%i in (`dir /B /L`) do set FN="%%i" && call :ProcessUserSubfolderItem 2>nul
  popd
goto :eof

:ProcessUserSubfolderItem
  if %FN%=="desktop.ini" goto :eof
  if %FN%=="my music" goto :eof
  if %FN%=="my pictures" goto :eof
  if %FN%=="my videos" goto :eof
  if %FN%=="мои видеозаписи" goto :eof
  if %FN%=="мои рисунки" goto :eof
  if %FN%=="моя музыка" goto :eof
  if %FN%=="nvidia corporation" goto :eof
  if %FN%=="sample music" goto :eof
  if %FN%=="sample pictures" goto :eof
  if %FN%=="sample media" goto :eof
  if %FN%=="sample videos" goto :eof

  echo %FN% | find ".lnk" >nul && goto :eof 
  echo "%CD:~2%\%FN:~1,-2%" >>%EF%
goto :eof

:AddException
  set E=%1
  echo "%CD:~2%\%E:~1,-1%" >>%EF%
goto :eof

:BackupFailed
echo Failed to generate exceptions list. Image is not captured.
exit 0
