#!/bin/sh

set -e

echo "Enter the releasing version(Tag name): "

read VERSION

echo # (optional) move to a new line

ask() {
  local prompt default reply

  if [ "${2:-}" = "Y" ]; then
    prompt="Y/n"
    default=Y
  elif [ "${2:-}" = "N" ]; then
    prompt="y/N"
    default=N
  else
    prompt="y/n"
    default=
  fi

  while true; do

    # Ask the question (not using "read -p" as it uses stderr not stdout)
    echo "$1 [$prompt] "

    # Read the answer (use /dev/tty in case stdin is redirected from somewhere else)
    read reply </dev/tty

    # Default?
    if [ -z "$reply" ]; then
      reply=$default
    fi

    # Check if the reply is valid
    case "$reply" in
    Y* | y*) return 0 ;;
    N* | n*) return 1 ;;
    esac

  done
}

#read -r -p "Deploying $VERSION - are you sure? (y/N) " response
#echo # (optional) move to a new line
if ask "Deploying $VERSION - are you sure?"; then

  mkdir temp_web

  cd temp_web

  git init

  git remote add ui-project git@github.com:linways/ui-project.git

  git fetch ui-project

  if [ "$VERSION" = "master-v4" ]; then
    git checkout ui-project/master-v4 -- dist
  else
    git checkout $VERSION -- dist
  fi

  rsync -r dist/. ../v4

  cd ../

  rm -rf temp_web

  echo # (optional) move to a new line

  echo "$VERSION deployed successfully"

else
  exit 128
fi
