#!/bin/bash

# make-dev-releases
# =================
#
# This script produces pre-releases on top of the current branch for the
# `dev` and `canal` versions (as per their npm tags).
#
# To use it:
#
#   1. Be sure that you're on the branch corresponding to the pre-release you
#      want to publish, at the repository's root directory.
#
#   2. Call this script.
#
#      You may optionally provide two arguments:
#
#        - the version number (e.g. 5.124.13)
#
#        - the "increment number", set to `00` by default (as is wanted for the
#          first and hopefully only release in a given day).
#
#          This is for cases where you're doing multiple releases in a single
#          day, allowing you to increment that value for each of these releases
#          and avoid release naming conflicts.
#
#      If you forget one of those arguments or both, the script will ask you
#      to enter those instead.
#
#   3. When the script asks you to confirm, check that the preceding commands
#      did not output any issue and if it didn't you can confirm.
#
#   4. That's it!
#
#      If everything goes right, dev releases will be generated server-side
#      once the right tag is created an pushed.

set -e

# Log a line to stderr and exit with error code 1
err() {
  echo "ERROR: $1" >&2
  exit 1
}

# Check that the given command is installed and quit on error if that's not the case
check_dependency() {
  if [ -z "$(command -v "$1")" ]; then
    err "This script needs \"$1\" to be installed and be executable"
  fi
}

check_dependency git
check_dependency echo
check_dependency npm
check_dependency sed
if [ -z "$EDITOR" ]; then
  err "Environment variable EDITOR is not set. Please set it to your preferred text editor."
fi

if [ $# -eq 0 ]; then
  read -r -p "Please enter the wanted version number (example: 4.12.1): " version
  echo ""
  if [ -z "${version}" ]; then
    # TODO SEMVER REGEX?
    err "Please enter a valid version number next time."
  fi
else
  version=$1
fi

if [ $# -lt 2 ]; then
  read -r -p "Please enter the increment number [by default: 00]: " incr
  if [ -z "${incr}" ]; then
    incr="00"
  fi
else
  incr=$2
fi

current_branch=$(git branch | sed -n -e 's/^\* \(.*\)/\1/p')
date=$(date "+%Y%m%d")
dev_version="${version}-dev.${date}${incr}"
canal_version="${version}-canal.${date}${incr}"

if [ -n "$(git status --porcelain)" ]; then
  err "There is unstaged changes in your worktree. Please commit your changes or stash them before creating the release."
fi

echo "This script will prepare dev RxPlayer versions: $dev_version and $canal_version"

if ! git apply --check "./scripts/canal-release.patch"; then
  echo "Error: Canal patch cannot be applied cleanly!"
  echo "Please resolve conflicts in the patch file before proceeding."
  exit 1
fi
echo "Canal patch check passed ✓"

echo "checking that the versions are not already published on npm..."
if npm view "rx-player@$dev_version" >/dev/null 2>&1; then
  err "Version already published to npm: $version-dev.${date}${incr}"
fi

if npm view "rx-player@$canal_version" >/dev/null 2>&1; then
  err "Version already published to npm: $version-canal.${date}${incr}"
fi

# Make dev Changelog
npm run releases:changelog -- -d "$dev_version"

$EDITOR CHANGELOG.md
echo "Running prettier on CHANGELOG.md..."
npx prettier --write CHANGELOG.md --log-level silent
echo ""

if [ -n "$(git status --porcelain CHANGELOG.md)" ]; then
  echo "-- Current CHANGELOG.md Status: --"
  echo ""
  git status CHANGELOG.md

  while :; do
    echo ""
    echo "We will push this CHANGELOG.md update to ${current_branch}."
    read -r -p "do you want to continue [y/d/s/a/c/t/h] (h for help) ? " -n1 REPLY
    echo ""

    if [[ $REPLY =~ ^[Hh](elp)?$ ]]; then
      echo ""
      echo ""
      echo "+- help -------------------------------------------------+"
      echo "| y: commit and continue                                 |"
      echo "| d: see diff                                            |"
      echo "| s: see status                                          |"
      echo "| a: abort script from here                              |"
      echo "| c: skip CHANGELOG.md update and go to the next step    |"
      echo "| h: see this help                                       |"
      echo "+--------------------------------------------------------+"
    elif [[ $REPLY =~ ^[Yy](es)?$ ]]; then
      git add CHANGELOG.md
      git commit -m "Update CHANGELOG.md for v$dev_version"
      break
    elif [[ $REPLY =~ ^[Dd](iff)?$ ]]; then
      git diff CHANGELOG.md || true # ignore when return 1
    elif [[ $REPLY =~ ^[Ss](tatus)?$ ]]; then
      git status CHANGELOG.md
    elif [[ $REPLY =~ ^[Aa](bort)?$ ]]; then
      echo "exiting"
      exit 0
    elif [[ $REPLY =~ ^[Cc](heckout)?$ ]]; then
      git checkout CHANGELOG.md
    else
      echo "invalid input"
    fi
  done
fi

if [ -n "$(git status --porcelain)" ]; then
  err "Unexpected diff in \"${current_branch}\""
fi

while true; do
  read -r -n1 -p "Do you wish to publish the dev and canal builds? [y/n] " yn
  echo ""
  case $yn in
  [Yy]*) break ;;
  [Nn]*) exit ;;
  *) echo "Please answer y or n." ;;
  esac
done

# TODO: Include release note as a tag description?
git tag -s -a "v${dev_version}" -m "RxPlayer dev release: v${dev_version}"
git push origin "${current_branch}"
