#!/bin/bash

#
# Script to create a new release using semantic-release

# ----------------------------------
# COLORS
# ----------------------------------
NOCOLOR='\033[0m'
RED='\033[0;31m'
GREEN='\033[0;32m'
ORANGE='\033[0;33m'
CYAN='\033[0;36m'
YELLOW='\033[1;33m'

# ----------------------------------
# CHECKING IF BRANCH IS UP-TO-DATE
# ----------------------------------
BRANCH=$(git rev-parse --abbrev-ref HEAD)
if [[ $BRANCH != "develop" ]]; then
  echo -e "${RED}Aborting script - you need to be in branch develop${NOCOLOR}";
  exit 1;
fi

if [[ `git status --porcelain` ]]; then
  echo -e "${RED}Aborting script - make sure you have committed and pushed everything to Git${NOCOLOR}";
  exit 1;
fi

# ----------------------------------
# EXIT WHEN ANY COMMAND FAILS
# ----------------------------------
set -e

function exitMessage()
{
  if [ $? -ne 0 ]; then
    echo -e "${RED}\"${last_command}\" command filed with exit code $?.${NOCOLOR}"
  fi
}

# keep track of the last executed command
trap 'last_command=$current_command; current_command=$BASH_COMMAND' DEBUG
# echo an error message before exiting
trap exitMessage EXIT


# ----------------------------------
# RUN ESLINT
# ----------------------------------
echo -e "${CYAN}Running e2e tests using Cypress${NOCOLOR}"
npm run lint
echo -e "${GREEN}Tests finished${NOCOLOR}"

# ----------------------------------
# TESTS
# ----------------------------------
echo -e "${CYAN}Running e2e tests using Cypress${NOCOLOR}"
npm run test
echo -e "${GREEN}Tests finished${NOCOLOR}"

# ----------------------------------
# SEMANTIC RELEASE
# ----------------------------------
if [ $1 == "dry" ]; then
  echo -e "${CYAN}Dry running Semantic Release${NOCOLOR}"
  npx semantic-release --no-ci --debug --dry-run -b develop
  echo -e "${GREEN}Dry run of Semantic Release complete${NOCOLOR}"
  exit
else
  echo -e "${CYAN}Running Semantic Release${NOCOLOR}"
  npx semantic-release --no-ci --debug -b develop
  echo -e "${GREEN}Semantic Release complete${NOCOLOR}"
fi

# ----------------------------------
# UPDATING CHANGELOG
# ----------------------------------
echo -e "${CYAN}Updating CHANGELOG inside assets directory${NOCOLOR}"
rm apps/mina-sidor-fa/src/assets/CHANGELOG.md
cp CHANGELOG.md apps/mina-sidor-fa/src/assets/CHANGELOG.md
git add apps/mina-sidor-fa/src/assets/CHANGELOG.md
git commit -m "chore(changelog): Updated CHANGELOG.md inside assets directory"
echo -e "${GREEN}CHANGELOG updated${NOCOLOR}"

# ----------------------------------
# UPDATING GIT REPOSITORIES
# ----------------------------------
echo -e "${CYAN}Updating git repository${NOCOLOR}"
git push
git checkout next
git pull
git merge develop
git push
git checkout develop
echo -e "${GREEN}Git repository updated!${NOCOLOR}"
echo -e "${GREEN}Release is complete!${NOCOLOR}"
