#!/bin/bash
# TODO - add option for output directory.
# Check for the parameter needed
if [[ $# -eq 0 ]] ; then
    echo "please pass the Option Tree path for conversion ex: /home/user/optiontrees/nxm"
    exit 1
fi
if [ -f $1/build.gradle ]; then
    echo "This directory seems to be converted already, exiting"
    exit 1
fi

optName=$(basename "$1")
nextmidasDir=`pwd`
optPath=$(readlink -m $1)
# Lets go to the option tree to do the work
cd $optPath 
parentDir="$(dirname $optPath)"
outputPath="${parentDir}/temp/${optName}"
echo "output path of new option tree = $outputPath"
mkdir -p "$outputPath/src/main/midas"
mkdir -p "$outputPath/src/test/midas"
mkdir -p "$outputPath/src/main/resources"
mkdir -p "$outputPath/src/test/resources"

#  Get to the level of the nxm folder. The standard structure of the option tree location is /path/to/folder/nxm/optname
cd ../../
pwd
for optSubDir in nxm/$optName/* ; do
  baseDirName=$(basename "$optSubDir")
  if [ "$baseDirName" = "test" ]; then
    cp -r --parents "${optSubDir}" "$outputPath/src/test/midas"
  elif [ "${baseDirName}" = 'cfg' ] || [ "${baseDirName}" = 'dat' ] || [ "${baseDirName}" = 'docs' ] || [ "${baseDirName}" = 'exp' ] || [ "${baseDirName}" = 'help' ] || [ "${baseDirName}" = 'rmif' ]; then
    cp -r --parents "${optSubDir}" "$outputPath/src/main/resources"
  else
    cp -r --parents "${optSubDir}" "$outputPath/src/main/midas"
  fi
done
echo "${outputPath}/build.gradle"
cp "$nextmidasDir/gradle/generic.gradle" "${outputPath}/build.gradle"

echo "***********Gradle conversion is complete************"

# tar the original code as a backup and delete the original code
cd nxm
tar -cf ${optName}.tar $optName
if [ ! $? -eq 0 ]; then 
  echo "unable to backup the previous codebase, exiting"
  exit 1
fi
rm -r $optPath
# move the temp code to the new location
mv $outputPath $optPath
rm -r "${parentDir}/temp"
# add the opt to the settings.gradle
grep -q -F "include ':$optName'" "$nextmidasDir/settings.gradle" || echo "include ':$optName'" >> $nextmidasDir/settings.gradle
grep -q -F "project(':$optName').projectDir = new File('$optPath')" $nextmidasDir/settings.gradle || echo "project(':$optName').projectDir = new File('$optPath')" >> $nextmidasDir/settings.gradle


