#!/bin/bash
######################################################################################
#
# This script handles the separation of lib-libg dependencies regarding
# NeXtMidas graphics-related functionality. Separation can be enabled
# (splitliblibg) or disabled (nsplitliblibg).
#
# This script takes in a swap mode argument, and based on the argument,
# if the corresponding set of txt files can be found within the swap
# parent directory, those files will be copied over into NMROOT as
# java files. These new java files will replace the current
# corresponding java files with the new corresponding java files.
#
# Usage: ${0} <split-or-nsplit>
#
# Author: Zachary Matthews
# Since:  NeXtMidas 4.1.3
#
######################################################################################

if [ $# -lt 1 ] ; then
  echo ""
  echo "Usage: ${0} <split-or-nsplit>"
  exit 1
fi

swap_arg=${1}
if [ ! ${swap_arg} == "split" ] && [ ! ${swap_arg} == "nsplit" ] ; then
  echo ""
  echo "Usage: ${0} <split-or-nsplit>"
  exit 1
fi

liblibg_parent_dir=`realpath ${0}` ; liblibg_parent_dir=`dirname ${liblibg_parent_dir}`
swap_mode_dir_name=${swap_arg}liblibg
NMROOT_TMP=`realpath ${0}`
for i in {1..4}
do
  NMROOT_TMP=`dirname ${NMROOT_TMP}`
done
NMROOT=${NMROOT_TMP}
nxm_repo=`basename ${NMROOT}`

# **********************************************************************
# Copy all files within the swap subdirectory to the temp directory,
# change them to java files, and move the java files into NMROOT
# to replace the corresponding files currently in NMROOT
# **********************************************************************
if [ ${swap_arg} == "split" ] ; then
  echo ""
  echo "Separating lib-libg dependencies..."
else
  echo ""
  echo "Restoring lib-libg dependencies..."
fi
cd ${liblibg_parent_dir}/${swap_mode_dir_name}
files_to_copy=`find . -type f -name "*.txt"` # assuming text files here in mode directory
for file in ${files_to_copy}
do
  opt_tree=`cut -d '/' -f2 <<< ${file}`           # get top-level option tree
  text_file=${file:2}                             # name of the text file without "./"
  java_file=${text_file::-4}.java                 # name of the java-file version of the text file
  cp --parents ${text_file} /tmp                  # preserve original parent directory structure (sys/...) 
  mv /tmp/${text_file} ${NMROOT}/nxm/${java_file} # convert files to java files as they're being moved over; for 'mv', files are overwritten in NMROOT by default
done
rm -rf /tmp/${opt_tree} # remove /tmp/<option_tree>
