#!/usr/bin/env bash

set -e

# For mac support
if ! which realpath >/dev/null; then
  realpath() {
    node -p "require('fs').realpathSync('${1}')"
  }
fi

main() {
  # setup using globals, defaulting where globals are not defined, assuming gitlab env values for further defaults
  local CHECK_BRANCH_NAME="${CHECK_BRANCH_NAME-${CI_DEFAULT_BRANCH-trunk}}"
  local CHECK_REMOTE_NAME="${CHECK_REMOTE_NAME-${CI_REMOTE_NAME-origin}}"
  local GIT_OBJECT="${GIT_OBJECT-${CHECK_REMOTE_NAME}/${CHECK_BRANCH_NAME}}"
  local THIS_DIR="$(dirname "$(realpath "${BASH_SOURCE[0]}")")"

  local PJ="${CHECK_PACKAGE_JSON-./package.json}"
  local PREV_PJSON=
  local V_NOW=
  local V_PREV=
  local V_SEL=${CHECK_VERSION_SELECTOR-.version}

  if PREV_PJSON="$(git show ${GIT_OBJECT}:${PJ} 2>&1)"; then
    if ! V_PREV="$(node -p "(${PREV_PJSON})${V_SEL}")"; then
      >&2 echo "Could not find a previous package.json version in JSON ${PREV_PJSON}"

      return 1
    fi
  else
    V_PREV=0.0.0

    >&2 echo "Could not find a previous package.json using git show ${GIT_OBJECT}:${PJ}, using ${V_PREV}"
  fi

  if ! V_NOW="$(node -p "require('${PJ}')${V_SEL}")"; then
    >&2 echo "Could not find a current version in ${PJ}"

    return 1
  fi

  if "${THIS_DIR}/semvers-increasing" "${V_PREV}" "${V_NOW}"; then
    >&2 echo "Version upgraded! (${V_PREV}->${V_NOW}) Great Success!"

    return 0
  else
    >&2 echo "Version not upgraded, :(. (current ${V_NOW} should be greater than previous ${V_PREV})"
    >&2 echo
    >&2 echo "Recommend running one of:"
    >&2 echo "  yarn version --patch # for non-breaking changes within the 0.x.x space or bugfixes >= 1.0.0"
    >&2 echo "  yarn version --minor # for breaking changes within the 0.x.x space or new features >= 1.0.0"
    >&2 echo "  yarn version --major # for breaking changes >= 1.0.0"
    >&2 echo
    >&2 echo "Otherwise, use --no-verify in order to bypass this check:"
    >&2 echo "  git commit --no-verify"
    >&2 echo

    return 1
  fi
}

main "$@"
