#!/bin/bash

##########################################################################
#
# Swaps java files and jar files with jdk-compatible code and jar files.
#
# Environment Variables:
#   NMROOT - Current NeXtMidas distribution
#
# Author: Zachary Matthews
# Since:  NeXtMidas 4.1.1
#
##########################################################################

# Get the java major version
javaFullVer=`${JAVAHOME}/bin/java -version 2>&1 | awk -F '"' '/version/ {print $2}'`
javaMajVer=`echo ${javaFullVer} | awk -F '.' '{print $1}'`
if [[ ${javaMajVer} -eq 1 ]]; then
  javaMajVer=`echo ${javaFullVer} | awk -F '.' '{print $2}'`
fi

# Loop over all option trees and check for the jdk_config.txt file in each one
for opt in $NMROOT/nxm/*; do
  opt=`basename $opt`
  jdk_config=$NMROOT/nxm/$opt/cfg/jdk_config.txt
  if [[ -f $jdk_config ]]; then
    while read line; do
      # Ignore blank lines and lines that are comments
      if [[ -z ${line} ]] || [[ $line =~ ^# ]] || [[ $line =~ ^! ]]; then
        continue
      fi

      # Get package and class or jar from each line read in
      pkg=`echo $line | awk -F '.' '{print $1}'`
      idx=${#pkg}
      class_or_jar=${line:${idx}+1}

      # Get and sort all files for the given class or jar in the given package
      files_with_ver=(`find ${NMROOT}/nxm/${opt}/${pkg} -name "${class_or_jar}*.jdk*[[:digit:]]"`)
      files_with_ver=(`printf '%s\n' "${files_with_ver[@]}"|sort`)

      # Do not attempt to swap if the files_with_ver list is empty
      if [ "${files_with_ver}" == "" ] ; then
        continue
      fi

      # Determine the file extension
      if [ "${pkg}" == "jars" ] ; then
        file_ext=jar
      else
        file_ext=java
      fi

      # Make the full path to the given class
      class_or_jar_filepath=${NMROOT}/nxm/${opt}/${pkg}/${class_or_jar}

      # If none of the swap-jdk files with version numbers support the current java version,
      # then just use the corresponding swap-jdk file ending in .jdk
      # Otherwise, loop over the whole set of swap-jdk files with version numbers
      num_files_with_ver=${#files_with_ver[@]}
      max_file_with_ver=${files_with_ver[${num_files_with_ver}-1]}
      max_ver_str="${max_file_with_ver: -2}"
      max_ver=10#${max_ver_str}
      if [[ ${max_ver} -lt ${javaMajVer} ]]; then
        cp ${class_or_jar_filepath}.jdk ${class_or_jar_filepath}.${file_ext}
      elif [[ ${max_ver} -eq ${javaMajVer} ]]; then
        cp ${class_or_jar_filepath}.jdk${max_ver_str} ${class_or_jar_filepath}.${file_ext}
      else
        for file_with_ver in "${files_with_ver[@]}"
        do
          ver_str="${file_with_ver: -2}"
          ver=10#${ver_str}
          if [[ ${ver} -ge ${javaMajVer} ]]; then
            cp ${class_or_jar_filepath}.jdk${ver_str} ${class_or_jar_filepath}.${file_ext}
            break
          fi
        done
      fi
    done < ${jdk_config}
  fi
done
