#!/bin/bash
(
if [[ -z "${NMROOT}" ]]; then
  echo "WARNING: NMROOT is not defined, using script working directory"
  NMROOT=$(dirname "$0")
  echo $NMROOT
fi
cd $NMROOT

# Clean up, remove files that are not necessary
gradle clean # NXM-3755 since NeXtMidas 4.0.1

# need to copy any changed non linked files and remove them whether linked or not
if [[ ! -L "common.gradle" ]]; then
  cp common.gradle gradle/
fi
rm common.gradle
if [[ ! -L "build.gradle" ]]; then
  cp build.gradle gradle/
fi
rm build.gradle

if [[ ! -L "settings.gradle" ]]; then
  cp settings.gradle gradle/
fi
rm settings.gradle
if [[ ! -L "gradle.properties" ]]; then
  cp gradle.properties gradle/
fi
rm gradle.properties

# remove .settings created by gradle
rm -r .settings

# bring any legacy project settings back
mv backuplegacy/.settings ./
mv backuplegacy/.project ./
mv backuplegacy/.classpath ./
#make the nxm dir to populate with the option trees
mkdir nxm
for d in ./* ; do

  optName=$(basename "$d")
  if [ "${optName}" == "gradle" ] || [ "${optName}" == "*" ] || [ ! -d "${optName}" ] || [ ! -f "${optName}/build.gradle" ] ; then
    continue
  fi
  # copy all the directories from the gradle format back to legacy format
  mkdir nxm/$optName
  if [ -d ${optName}/src/main/midas/nxm ]; then 
    rsync -a ${optName}/src/main/midas/nxm ./ 
  fi
  if [ -d ${optName}/src/main/resources/nxm  ]; then 
    rsync -a ${optName}/src/main/resources/nxm ./
  fi
  if [ -d ${optName}/src/test/midas/nxm  ]; then 
    rsync -a ${optName}/src/test/midas/nxm ./
  fi
  if [ -d backuplegacy/${optName}  ]; then 
    rsync -a backuplegacy/${optName} nxm/
  fi
  # remove the gradle option tree once complete
  rm -rf $optName

done

rm -r backuplegacy
if [ -f xbc.tar ]; then
  tar -xf xbc.tar
  rm xbc.tar
fi
if [ -f gradle ]; then
  rm -r gradle
fi
if [ -f gradlew ]; then
  rm -r gradlew
fi
if [ -f gradlew.bat ]; then
  rm -r gradlew.bat
fi
if [ -d bin ]; then
  rm -r bin
fi

#update the .git to track the files again
if [ -d ".git" ]; then
  git ls-files -z nxm/ | xargs -0 git update-index --no-assume-unchanged
fi
)