#!/usr/bin/env bash

declare -a ARGS=("${@}")

ISMACOS=0
if [ "$( uname -s )" = "Darwin" ]; then
  ISMACOS=1
fi

# check for headless mode
HEADLESS=0
GUI=0
HELP=0
DEBUG=0
for RAWARG in "${@}"; do
  ARG="${RAWARG%%=*}"
  case "${ARG}" in
    --headless|--output|--image|--structureimage)
      HEADLESS=1
      ;;
    --help|--help-*|--version|-h)
      HELP=1
      HEADLESS=1
      ;;
    --gui)
      GUI=1
      ;;
    --debug)
      DEBUG=1
      ;;
  esac
done
if [ "${HELP}" = 1 ]; then
  # --help takes precedence
  GUI=0
elif [ "${GUI}" = 1 ]; then
  # --gui takes precedence over --headless
  HEADLESS=0
fi

# this whole next part is because there's no readlink -f in Darwin
function readlinkf() {
  FINDFILE="$1"
  FILE="${FINDFILE}"
  PREVFILE=""
  C=0
  MAX=100 # just in case we end up in a loop
  FOUND=0
  while [ "${C}" -lt "${MAX}" -a "${FILE}" != "${PREVFILE}" -a "${FOUND}" -ne 1 ]; do
    PREVFILE="${FILE}"
    FILE="$(readlink "${FILE}")"
    if [ -z "${FILE}" ]; then
      # the readlink is empty means we've arrived at the script, let's canonicalize with pwd
      FILE="$(cd "$(dirname "${PREVFILE}")" &> /dev/null && pwd -P)"/"$(basename "${PREVFILE}")"
      FOUND=1
    elif [ "${FILE#/}" = "${FILE}" ]; then
      # FILE is not an absolute path link, we need to add the relative path to the previous dir
      FILE="$(dirname "${PREVFILE}")/${FILE}"
    fi
    C=$((C+1))
  done
  if [ "${FOUND}" -ne 1 ]; then
    echo "Could not determine path to actual file '$(basename "${FINDFILE}")'" >&2
    exit 1
  fi
  echo "${FILE}"
}

# args for the JVM
declare -a JVMARGS=()

JAVABIN=""
# set vars for being inside the macos App Bundle
if [ "${ISMACOS}" = 1 ]; then
# MACOS ONLY
  SCRIPT="$(readlinkf "$0")"
  DIR="$(dirname "${SCRIPT}")"
  APPDIR="${DIR%/bin}"

  if [ -d "${APPDIR}/jre" ]; then
    JREDIR="${APPDIR}/jre"
  elif [ -e "${APPDIR}/installer.properties" ]; then
    INSTALLERAPPDIR="$( grep -E "^installer.appdir[[:space:]]*=[[:space:]]*" "${APPDIR}/installer.properties" | sed -E 's/^installer.appdir[[:space:]]*=[[:space:]]*//' )"
    if [ -d "${INSTALLERAPPDIR}/jre" ]; then
      JREDIR="${INSTALLERAPPDIR}/jre"
    fi
  fi
  if [ ! -z "$JREDIR" ]; then
    JAVABIN="${JREDIR}/Contents/Home/bin"
  fi
  if [ "${HEADLESS}" != 1 ]; then
    JVMARGS=( "${JVMARGS[@]}" "-Xdock:icon=${APPDIR}/resource/jalview_logo.png" )
  fi
else
# NOT MACOS
  SCRIPT="$(readlink -f "$0")"
  DIR="$(dirname "${SCRIPT}")"
  APPDIR="${DIR%/bin}"
  if [ -d "${APPDIR}/jre" ]; then
    JAVABIN="${APPDIR}/jre/bin"
  elif [ -e "${APPDIR}/installer.properties" ]; then
    INSTALLERAPPDIR="$( grep -E "^installer.appdir[[:space:]]*=[[:space:]]*" "${APPDIR}/installer.properties" | sed -E 's/^installer.appdir[[:space:]]*=[[:space:]]*//' )"
    if [ ! -z "$INSTALLERAPPDIR" -a -d "${INSTALLERAPPDIR}/jre" ]; then
      JAVABIN="${INSTALLERAPPDIR}/jre/bin"
    fi
  fi
fi
JAVA="${JAVABIN}/java"

# headless java arguments
if [ "${HEADLESS}" = 1 ]; then
  # not setting java.awt.headless in java invocation of running jalview due to problem with Jmol
  if [ "${HELP}" = 1 ]; then
    JVMARGS=( "${JVMARGS[@]}" "-Djava.awt.headless=true" )
  fi
  # this suppresses the Java icon appearing in the macOS Dock
  if [ "${ISMACOS}" = 1 ]; then
    JVMARGS=( "${JVMARGS[@]}" "-Dapple.awt.UIElement=true" )
  fi
fi

SYSJAVA=java
GETDOWNTXT="${APPDIR}/getdown.txt"
CHANNELPROPS="${APPDIR}/channel.props"
NAME="$( grep app_name= "${CHANNELPROPS}" | cut -d= -f2 )"

CLASSPATH=""
# save an array of JAR paths in case we're in WSL (see later)
declare -a JARPATHS=()

# look for getdown.txt -- needed to create classpath
if [ ! -e "${GETDOWNTXT}" ]; then
  echo "Cannot find ${GETDOWNTXT}" >&2
  exit 3
fi

# launching Jalview with jalview.bin.Launcher instead of getdown-launcher.jar
CLASS="jalview.bin.Launcher"

# get classpath from the code= entries in getdown.txt
# always check grep and sed regexes on macos -- they're not the same
for JAR in $(grep -e '^code[[:space:]]*=[[:space:]]*' "${GETDOWNTXT}" | while read -r line; do echo $line | sed -E -e 's/code[[:space:]]*=[[:space:]]*//;'; done);
do
  [ -n "${CLASSPATH}" ] && CLASSPATH="${CLASSPATH}:"
  CLASSPATH="${CLASSPATH}${APPDIR}/${JAR}"
  JARPATHS=( "${JARPATHS[@]}" "${APPDIR}/${JAR}" )
done

COLUMNS=80
# get console width -- three ways to try, just in case (not needed for update)
if command -v tput 2>&1 >/dev/null; then
  COLUMNS=$(tput cols) 2>/dev/null
elif command -v stty 2>&1 >/dev/null; then
  COLUMNS=$(stty size | cut -d" " -f2) 2>/dev/null
elif command -v resize 2>&1 >/dev/null; then
  COLUMNS=$(resize -u | grep COLUMNS= | sed -e 's/.*=//;s/;//') 2>/dev/null
fi
JVMARGS=( "${JVMARGS[@]}" "-DCONSOLEWIDTH=${COLUMNS}" )
JVMARGS=( "${JVMARGS[@]}" "-Dgetdownappdir=${APPDIR}" )
JVMARGS=( "${JVMARGS[@]}" "-Dlauncher.script=${SCRIPT}" )
JVMARGS=( "${JVMARGS[@]}" "-Dinstaller.appdir=${APPDIR}" )

JAVAEXT=""
# WINDOWS ONLY in Cygwin or Windows Subsystem for Linux (WSL)
# change paths for Cygwin or WSL
if [ "${ISMACOS}" != 1 ]; then # older macos doesn't like uname -o, best to avoid
  if [ "$(uname -o)" = "Cygwin" ]; then # Cygwin
  # CYGWIN
    CLASSPATH=$(cygpath -pw "${CLASSPATH}")
    # now for some arg paths fun. only translating paths starting with './', '../', '/' or '~'
    ARGS=()
    for ARG in "${@}"; do
      if [ "${ARG}" != "${ARG#@(/|./|../|~)}" ]; then
        ARGS=( "${ARGS[@]}" "$(cygpath -aw "${ARG}")" )
      else
        ARGS=( "${ARGS[@]}" "${ARG}" )
      fi
    done
  elif uname -r | grep -i microsoft | grep -i wsl >/dev/null; then # WSL
  # WSL
    CLASSPATH=""
    for JARPATH in "${JARPATHS[@]}"; do
      [ -n "${CLASSPATH}" ] && CLASSPATH="${CLASSPATH};"
      CLASSPATH="${CLASSPATH}$(wslpath -aw "${JARPATH}")"
    done
    ARGS=()
    for ARG in "${@}"; do
      if [ "${ARG}" != "${ARG#@(/|./|../|~)}" ]; then
        # annoyingly wslpath does not work if the file doesn't exist!
        ARGBASENAME="$(basename "${ARG}")"
        ARGDIRNAME="$(dirname "${ARG}")"
        ARGS=( "${ARGS[@]}" "$(wslpath -aw "${ARGDIRNAME}")\\${ARGBASENAME}" )
      else
        ARGS=( "${ARGS[@]}" "${ARG}" )
      fi
    done
    JAVAEXT=".exe"
    JAVA="${JAVA}${JAVAEXT}"
    SYSJAVA="java${JAVAEXT}"
  fi
fi

# look for bundled JRE. Might not be there if unix installer used in which case just invoke "java"
if [ ! -z "${JAVABIN}" -a -e "${JAVABIN}/${NAME}${JAVAEXT}" ]; then
  JAVA="${JAVABIN}/${NAME}${JAVAEXT}"
fi
# If not just try one in the PATH (we need .exe in WSL, added above)
if [ -z "${JAVABIN}" -o ! -e "${JAVA}" ]; then
  JAVA="${SYSJAVA}"
  echo "Cannot find bundled ${JAVA}, using system ${SYSJAVA} and hoping for the best!" >&2
fi

# This is just needed for display purposes
function quotearray() {
  QUOTEDVALS=""
  for VAL in "${@}"; do
    if [ ! "$QUOTEDVALS" = "" ]; then
      QUOTEDVALS="${QUOTEDVALS} "
    fi
    QUOTEDVALS="${QUOTEDVALS}\"${VAL}\""
  done
  echo $QUOTEDVALS
}

# for the debug command display
JVMARGSSTR=$(quotearray "${JVMARGS[@]}")
ARGSSTR=$(quotearray "${ARGS[@]}")

if [ "${DEBUG}" = 1 ]; then
 echo Shell running: \""${JAVA}"\" ${JVMARGSSTR} -cp \""${CLASSPATH}"\" \""${CLASS}"\" ${ARGSSTR} >&2
fi

"${JAVA}" "${JVMARGS[@]}" -cp "${CLASSPATH}" "${CLASS}" "${ARGS[@]}"
