#!/usr/bin/env bash

VERSION=$1
echo "------------------"

if [[ -z $VERSION ]]; then
  echo "- Will not upload to NPM (no version specified)"
  exit 0
fi

if [[ ! -f ~/.npmrc ]]; then
  echo "- No credentials for NPM Publish are present in ~/.npmrc"
  exit 203
fi

RAWPKG="${SOURCEROOT}/${NAME}/package.json"
NPMPCK="${SOURCEROOT}/${NAME}/npm-package.json"

if [[ -f ${RAWPKG}.template ]]; then
  echo "- Using package.json template"
  # shellcheck disable=SC2016
  envsubst '${VERSION}' <"${NPMPCK}.template" >"${TEMPDEST}/package.json"
elif [[ -f ${RAWPKG} ]]; then
  echo "- Will not upload to NPM as there is a static package.json"
  exit 202
elif [[ -f "${NPMPCK}.template" ]]; then
  echo "- Using npm-package template"
  # shellcheck disable=SC2016
  envsubst '${VERSION}' <"${NPMPCK}.template" >"${TEMPDEST}/package.json"
elif [[ -f "${NPMPCK}" ]]; then
  echo "- Using static npm-package.json"
  cp "${NPMPCK}" "${TEMPDEST}/package.json"
else
  echo "- Will not upload to NPM"
  exit 201
fi

if [[ -f "${TEMPDEST}/package.json" ]]; then

  echo "- Uploading to NPM"
  echo
  # publish NPM PACKAGE
  cd "${TEMPDEST}" || exit 200
  cat "${TEMPDEST}/package.json"

  # do not include debug version in NPM
  # rm lib.debug.js

  npm publish && {
    echo "👌 package uploaded to NPM"
  }

fi
