#!/usr/bin/env bash
# shellcheck source=scripts/functions
source "$(dirname "${0}")"/../functions

# $1: optional setup
function doSetup() {
  if command -v npm &> /dev/null
  then
    if [ -n "${1}" ]
    then
      doEcho "npm is already installed at $(command -v npm)"
    fi
  else
    doDevonCommand node -q setup
  fi
}

function doGetProjectVersion() {
  if [ -f package.json ]
  then
    local version_line
    version_line="$(grep "\"version\"" package.json)" || doFail "Could not determine your version! Please check your package.json."
    # shellcheck disable=SC2001
    echo "${version_line}" | sed "s/.*:[ ]*\"\([^\"]*\)\".*/\1/"
  else
    doFail "No package.json - not an npm project."
  fi
}

function doSetProjectVersion() {
  if [ -f package.json ]
  then
    cp package.json package.json.bak
    sed "s/\"version\"\:[ ]*\"[^\"]*\"/\"version\": \"${1}\"/" package.json.bak > package.json
    rm package.json.bak
  else
    doFail "No package.json - not an npm project."
  fi
}

function doCheckTopLevelProject() {
  if [ ! -f package.json ]
  then
    doFail "No package.json - not an npm project."
  fi
  # IMHO npm/package.json does not support nested projects (modules)
}

function doRunBuild() {
  doSetup
  local extra_arg=""
  if [ ! -d node_modules ] && [[ "${*}" != *install* ]]
  then
    extra_arg="install"
  fi
  doEcho "Running: npm ${extra_arg} ${*}"
  if doIsQuiet
  then
    npm --quiet ${extra_arg} "${@}"
  else
    npm ${extra_arg} "${@}"
  fi
}

#CLI
if [ "${1}" = "-h" ] || [ "${1}" = "help" ]
then
  echo "Setup or run npm."
  echo
  echo "Arguments:"
  echo "                      run default build"
  echo "setup                 setup angular-cli (install and verify)"
  echo "«args»                call maven with the specified arguments"
  echo
  echo "Options:"
  exit
fi
if [ -z "${1}" ]
then
  # shellcheck disable=SC2086
  doRunBuild ${NPM_BUILD_OPTS:-build}
elif [ "${1}" = "setup" ]
then
  doSetup setup
else
  if [ "${1}" = "get-version" ]
  then
    doGetProjectVersion
  elif [ "${1}" = "set-version" ] && [ -n "${2}" ]
  then
    shift
    doSetProjectVersion "${@}"
  elif [ "${1}" = "check-top-level-project" ]
  then
    shift
    doCheckTopLevelProject "${@}"
  elif [ "${1}" = "release" ]
  then
    # shellcheck disable=SC2086
    doRunBuild ${NPM_RELEASE_OPTS:-release}
  else
    doRunBuild "${@}"
  fi
fi
