#!/bin/bash
# global variables
cr="\033[0m"
cfby="\033[1;33m"
pub="$NPM_PUSH_PUBLISH"
ver="$NPM_PUSH_VERSION"
rep="$NPM_PUSH_REPOSITORY"
pre="$NPM_PUSH_PREFIX"
msg="$NPM_PUSH_MESSAGE"
repurl=""

psd() {
  # present script directory
  z="${BASH_SOURCE[0]}"
  if [ -h "$z" ]; then z="$(readlink "$z")"; fi
  cd "$(dirname "$0")" && cd "$(dirname "$z")" && pwd
}

# read arguments
dp0="$(psd)/"
for a in "$@"; do
  if [[ "$a" == "-p" ]] || [[ "$a" == "--publish" ]]; then pub="1"
  elif [[ "$a" == "-0" ]] || [[ "$a" == "--check" ]]; then ver="check"
  elif [[ "$a" == "-1" ]] || [[ "$a" == "--patch" ]]; then ver="patch"
  elif [[ "$a" == "-2" ]] || [[ "$a" == "--minor" ]]; then ver="minor"
  elif [[ "$a" == "-3" ]] || [[ "$a" == "--major" ]]; then ver="major"
  elif [[ "$a" == "-r" ]] || [[ "$a" == "--repository" ]]; then rep="1"
  elif [[ "$a" == "--help" ]]; then less "${dp0}README.md" && exit
  else msg="$a"
  fi
done

# save changes
if [[ "$ver" == "" ]]; then ver="patch"; fi
if [[ "$rep" == "1" ]]; then repurl="$(git config --get remote.origin.url)"; fi
pver=$(node "${dp0}amend" ${ver} ${repurl})
git add . >/dev/null 2>&1

# publish to npm
printf "${cfby}npm publish${cr}\n"
if [[ "$pub" == "1" ]]; then
  npm publish
fi

# push to github
printf "${cfby}git push${cr}\n"
if [[ "$msg" == "" ]]; then msg="$pver"; fi
if [[ "$pre" != "" ]]; then msg="$pre $msg"; fi
git commit -m "$msg"
git push
