#!/bin/bash
#######################################################################################
#
# This scripts moves the jars pulled from Nexus into each of their respective option
# trees on the baseline.
#
# Author: Zachary Matthews
# Since:  NextMidas 4.1.4
#
#######################################################################################

pulljars_parent_dir=`realpath ${0}` ; pulljars_parent_dir=`dirname ${pulljars_parent_dir}`
NMROOT_TMP=`realpath ${0}`
for i in {1..2}
do
  NMROOT_TMP=`dirname ${NMROOT_TMP}`
done
NMROOT=${NMROOT_TMP}

usage()
{
cat <<EOF
usage: ${0} options
This script will fetch an artifact from a Nexus server using the Nexus REST redirect service.
OPTIONS:
   -h    Show this message
   -d    Print debug information
   -l    Alternative locations for option trees (i.e. opt1,dir1,opt2,dir2)
EOF
}

# Read in Complete Set of parameters
DEBUG=false
ALT_LOCATIONS_LIST=

while getopts "hdl:" OPTION
do
  case ${OPTION} in
    h) usage; exit 0;;
    d) DEBUG=true;;
    l) ALT_LOCATIONS_LIST=${OPTARG};;
    ?) echo "Illegal argument ${OPTION}=${OPTARG}" >&2; usage; exit 1;;
  esac
done

# print out debug information
if [[ ! "${DEBUG}" == "" ]] ; then
  echo ""
  echo "******* DEBUG INFORMATION *******"
  echo "ALT_LOCATIONS_LIST: ${ALT_LOCATIONS_LIST}"
  echo "*********************************"
fi

OIFS=${IFS}
IFS=","
NXM_OPTS=( ${NXM_OPTS_LIST} )
if [[ "${ALT_LOCATIONS_LIST}" != "" ]] ; then
  ALT_LOCATIONS=( ${ALT_LOCATIONS_LIST} )
fi
IFS=${OIFS}

cd ${pulljars_parent_dir}/jars

jarDirs=( `find . -maxdepth 1 -type d` )

for jarDir in "${jarDirs[@]}"
do
  if [[ "${jarDir}" == "." ]] ; then
    continue
  else
    opt=`basename "${jarDir}"`
    if [[ -d ${NMROOT}/nxm/${opt}/jars ]] ; then
      echo ""
      echo "Moving all jar files in ${pulljars_parent_dir}/jars/${opt} into ${NMROOT}/nxm/${opt}/jars..."
      mv ${opt}/*.jar ${NMROOT}/nxm/${opt}/jars
      echo "Removing directory ${pulljars_parent_dir}/jars/${opt}..."
      rm -rf ${pulljars_parent_dir}/jars/${opt}
    else
      for idx in "${!ALT_LOCATIONS[@]}"
      do
        DESTINATION_DIR=
        if [[ "${ALT_LOCATIONS[${idx}]}" == "${opt}" ]] ; then
          DESTINATION_DIR=${ALT_LOCATIONS[${idx+1}]}
          break
        fi
      done
      if [[ "${DESTINATION_DIR}" != "" ]] ; then
        echo ""
        echo "Moving all jar files in ${pulljars_parent_dir}/jars/${opt} into ${DESTINATION_DIR}/jars..."
        mv ${pulljars_parent_dir}/jars/${opt}/*.jar ${DESTINATION_DIR}/jars
        echo "Removing directory ${pulljars_parent_dir}/jars/${opt}..."
        rm -rf ${pulljars_parent_dir}/jars/${opt}
      else
        echo ""
        echo "WARNING: ${NMROOT}/nxm/${opt}/jars not found, and no alternative location specified for ${opt}."
      fi
    fi
  fi
done
