#!/bin/bash

set -e
PROG_NAME=$(basename "$0")

function usage()
{
  echo "USAGE: ${PROG_NAME} [-w] [-spark] [--no-profile]"
  exit $1
}

function parse_args()
{
  [ "$1" = "-h" ] && usage 0

  while [[ $# -gt 0 ]]; do
    case $1 in
      -w)
        USE_WGET=1
        shift
        ;;
      --no-profile)
        NO_PROFILE=1
        shift
        ;;
      -spark)
        DO_INSTALL_SPARK=1
        shift
        ;;
      *) echo "ERROR: invalid argument $1" && usage 1 ;;
    esac
  done

  # SMV version is updated automatically by smv-release
  SMV_VERSION="2r11"

  SMV_DIR="SMV"
  SMV_PROFILE_FILENAME="smv-profile.sh"
  SMV_PROFILE="${HOME}/.smv/${SMV_PROFILE_FILENAME}"

  SPARK_DIR="Spark"

  validate_version
}

# make sure version is of the format a.b.c.d where a,b,c,d are all numbers.
function validate_version()
{
  local ver="$1"
  local res=$(echo "$ver" | sed -E -e 's/^[0-9](\.[0-9]){0,2}r[0-9]+$//')
  if [ -n "$res" ]; then
    echo "ERROR: invalid version format: $ver"
    usage 1
  fi
}

# downloads and extracts the contents of a remote tar ball into current directory.
# System must have
# and, optionally, a checkable binary path to determine if the binary has
# already been installed
## Arg1 - URL
install_app() {
  local remote_tarball="$1"
  local local_tarball=$(basename $remote_tarball)

  # setup `curl` and `wget` silent options if we're running on Jenkins
  local curl_opts="-L"
  local wget_opts=""
  if [ -n "$AMPLAB_JENKINS" ]; then
    curl_opts="-s --fail ${curl_opts}"
    wget_opts="--quiet ${wget_opts}"
  else
    curl_opts="--progress-bar --fail ${curl_opts}"
    wget_opts="--progress=bar:force ${wget_opts}"
  fi

  if [ "$(type -p curl)" -a -z "${USE_WGET}" ]; then
    echo "[INFO] exec: curl ${curl_opts} ${remote_tarball}"
    curl ${curl_opts} "${remote_tarball}" > "${local_tarball}"
  elif [ "$(type -p wget)" ]; then
    echo "[INFO] exec: wget ${wget_opts} ${remote_tarball}"
    wget ${wget_opts} -O "${local_tarball}" "${remote_tarball}"
  else
    echo "[ERROR] must have curl or wget installed to install SMV"
    exit 2
  fi

  tar -zxf "$local_tarball"
  rm -rf "$local_tarball"
  echo "[INFO] $local_tarball was downloaded successfully!"
}

# Download the latest SMV binary release from github
download_smv() {
  install_app "https://github.com/TresAmigosSD/SMV/releases/download/v${SMV_VERSION}/smv_v${SMV_VERSION}.tgz"
}

# Download prebuilt spark version with hive support.
download_spark() {
  ${SMV_DIR}/tools/spark-install --target-dir ${SPARK_DIR}
}

jre_installtion_validation() {
  if [ -z $(type -p java) ]; then
    echo "[ERROR] java not found in path"
    exit 1
  fi

  JAVA_VER=$(java -version 2>&1 | sed -E 's/(java|openjdk) version "(.*)\.(.*)\..*"/\2\3/; 1q')
  if [ "$JAVA_VER" -lt 17 ]; then
    echo "[ERROR] JDK version less than 1.7"
  else
    echo "[INFO] JDK installation is correct"
  fi
}

python_installation_validation() {
  if [ -z $(type -p python) ]; then
    echo "[ERROR] python not found in path"
    exit 1
  fi

  PYTHON_VER=$(python --version 2>&1 | awk '{print $2}' | cut -f1-2 -d. | tr -d .)
  if [ "$PYTHON_VER" -lt 26 ]; then
    echo "[ERROR] SMV currently requires python >= v2.6"
    exit 1
  else
    echo "[INFO] python installation is correct"
  fi
}

generate_profile_file() {
  mkdir -p $(dirname ${SMV_PROFILE})
  local install_dir=`pwd`
  echo "# Autogenerated by smv-install script: `date`" > ${SMV_PROFILE}
  echo 'export PATH="'${install_dir}/${SMV_DIR}/tools':${PATH}"' >> ${SMV_PROFILE}
  if [ -n "$DO_INSTALL_SPARK" ]; then
    echo 'export PATH="'${install_dir}/${SPARK_DIR}/bin':${PATH}"' >> ${SMV_PROFILE}
  fi
  echo "[INFO] created ${SMV_PROFILE}"
  COPIED_SMV_PROFILE_PATH="${SMV_DIR}/tools/${SMV_PROFILE_FILENAME}"
  cp "${SMV_PROFILE}" "${COPIED_SMV_PROFILE_PATH}"
  echo "[INFO] copied SMV profile to ${COPIED_SMV_PROFILE_PATH}"
}

# add a call in users "profile" file to source the generated SMV profile file
source_profile_file() {
  local user_profiles=".bash_profile .bash_login .bashrc .profile"
  local found_profile=""
  for up in $user_profiles; do
    if [ -f "${HOME}/${up}" ]; then
      found_profile="${HOME}/${up}"
      break
    fi
  done

  if [ -z "$found_profile" ]; then
    echo "[ERROR]: could not find any profile file: $user_profiles"
    exit 1
  fi

  if grep -q -- "---SMV PROFILE----" $found_profile; then
    echo "[INFO] SMV profile alredy sourced in $found_profile"
  else
    echo >> $found_profile
    echo "#---SMV PROFILE----" >> $found_profile
    echo "source ${SMV_PROFILE}" >> $found_profile
    echo "[INFO] SMV profile sourced in $found_profile"
    echo "[INFO] Start a new shell or run \"source $found_profile\" to use SMV"
  fi
}

###############################################################################
# --- MAIN ---
###############################################################################

parse_args "$@"
jre_installtion_validation
python_installation_validation
download_smv
[ -n "$DO_INSTALL_SPARK" ] && download_spark
if [ -z "$NO_PROFILE" ]; then
  generate_profile_file
  source_profile_file
fi
