@echo off
setlocal enabledelayedexpansion
cd %NMROOT%

rem Clean up, remove files that are not necessary
call gradle clean

rem need to copy any changed files and remove them
copy build.gradle gradle /Y
del build.gradle
copy common.gradle gradle /Y
del common.gradle
copy settings.gradle gradle /Y
del settings.gradle
copy gradle.properties gradle /Y
del gradle.properties

rem remove .settings created by gradle
rmdir /s /q .settings

rem bring any legacy project settings back
move backuplegacy\.settings %cd%
if exist backuplegacy\.project move backuplegacy\.project %cd%
move backuplegacy\.classpath %cd%

rem make the nxm dir to populate with the option trees
mkdir nxm

for /f  %%G in ('dir /b /a:d') do (
  set cont=
  if /I "%%G" == "" ( set cont=false ) 
  if /I  %%G  == gradle ( set cont=false )  
  if not exist %%G\build.gradle ( set cont=false )

  if not defined cont set cont=true
  if /I !cont! == true (
    rem copy all the directories from the gradle format back to legacy format
    mkdir nxm\%%G
    if exist %%G\src\main\resources\nxm\%%G (
      for /f %%e in ('dir /b /a:d %%G\src\main\resources\nxm\%%G') do (
        xcopy /y /i /s /e %%G\src\main\resources\nxm\%%G\%%e nxm\%%G\%%e
      )
      for /f "usebackq delims=" %%e in (`dir /b /a:-d %%G\src\main\resources\nxm\%%G 2^>nul`) do (
        copy %%G\src\main\resources\nxm\%%G\%%e nxm\%%G /Y
      )
    )
    if exist %%G\src\test\midas\nxm\%%G (
      for /f %%e in ('dir /b /a:d %%G\src\test\midas\nxm\%%G') do (
        xcopy /y /i /s /e %%G\src\test\midas\nxm\%%G\%%e nxm\%%G\%%e
      )
      for /f "usebackq delims=" %%e in (`dir /b /a:-d %%G\src\test\midas\nxm\%%G 2^>nul`) do (
        copy %%G\src\test\midas\nxm\%%G\%%e nxm\%%G /Y
      )
    )
    if exist %%G\src\main\midas\nxm\%%G (
      for /f %%e in ('dir /b /a:d %%G\src\main\midas\nxm\%%G') do (
        if not %%e == test (
          xcopy /y /i /s /e %%G\src\main\midas\nxm\%%G\%%e nxm\%%G\%%e
        )
      )
      for /f "usebackq delims=" %%e in (`dir /b /a:-d %%G\src\main\midas\nxm\%%G 2^>nul`) do (
        copy %%G\src\main\midas\nxm\%%G\%%e nxm\%%G /Y
      )
    )
    if %%G == sys (
      if exist %%G\src\main\midas\tools (
        xcopy /y /i /s /e %%G\src\main\midas\tools tools
      )
    )
    rem remove the gradle option tree once complete
    rmdir /s /q %%G
  )
)

rmdir /s /q backuplegacy
tar -xf xbc.tar -C nxm
del xbc.tar
if exist gradlew.bat del gradlew.bat
if exist bin\        rmdir /s /q bin