#!/bin/sh

set -e

level=$0

if [ -n $level ]; then
  level="$(conventional-recommended-bump -p angular -h)"
fi

echo "Bump version and commit to git"
echo 

semver="semver"
json="json"

if [ "$(command -v semver)" == "" ]; then
  semver="./node_modules/.bin/semver"
fi

if [ "$(command -v json)" == "" ]; then
  json="./node_modules/.bin/json"
fi

function print_versions {
  if [ ! -f "$PWD/package.json" ]; then
    echo "Unable to find package.json"
    exit 1
  fi

  curr_ver="$(cat $PWD/package.json | $json .version)"
  next_ver="$($semver -i $level $curr_ver)" 

  echo "Current version: $curr_ver"
  echo "Next version: $next_ver"

  if [ "$CI" != "true" ]; then
    read -p 'Would you like to commit to git and push to remote server (yes/no)? ' approve_commit
  else
    approve_commit="yes"
  fi
}

function commit {
  print_versions

  curr_ver="$(cat $PWD/package.json | $json .version)"
  next_ver="$($semver -i $level $curr_ver)"

  if [ "$approve_commit" == "yes" ]; then
    npm --no-git-tag-version version $next_ver

    git add package.json package-lock.json
    git commit --no-verify --message "Bump version to v$next_ver [skip ci]"
  fi
}

function bump_ver {
  if [ "$CIRCLECI" == "true" ]; then
    if [ "$(git config --global user.email)" == "" ]; then
      git config --global user.email "circleci@bets.io"
      git config --global user.name "Circle CI"
    fi

    if [ "$CIRCLE_GITHUB_TOKEN" == "" ]; then
      echo "CIRCLE_GITHUB_TOKEN env variable was not specified but required"
      exit 1
    fi

    repo="/tmp/repo"
    rm -rf $repo
    branch=$CIRCLE_BRANCH
    git clone https://$CIRCLE_GITHUB_TOKEN@github.com/$CIRCLE_PROJECT_USERNAME/$CIRCLE_PROJECT_REPONAME -b $branch $repo
    cd $repo
    git branch
    
    commit
    git push origin $branch
  elif [ "$GITLAB_CI" == "true" ]; then
    echo "Gitlab CI"

    if [ "$GITLAB_TOKEN" == "" ]; then
      echo "GITLAB_TOKEN env variable was not specified but required"
      exit 1
    fi

    repo="/tmp/repo"
    branch=master
    rm -rf $repo
    git clone "https://gitlab-token:$GITLAB_TOKEN@gitlab.com/$CI_PROJECT_PATH.git" -b $branch $repo
    cd $repo
    
    if [ "$(git config user.email)" == "" ]; then
      GITLAB_USER_EMAIL=${GITLAB_USER_EMAIL:-"vitaly.krivtsov@bets.io"}
      GITLAB_USER_NAME=${GITLAB_USER_NAME:-"Vitaly Krivtsov"}

      git config user.email "$GITLAB_USER_EMAIL"
      git config user.name "$GITLAB_USER_NAME"
    fi

    commit
    git push origin $branch
  else
    commit
  fi
}

if [ "$GITLAB_CI_TEST" == "yes" ]; then
  export GITLAB_CI=true
  export CI=true
  export CI_PROJECT_PATH="skinholdings/drakemall-semantic-release"

  bump_ver
else 
  echo 1
  bump_ver
fi