#! /bin/bash

# Check if the script is running on the api-server
CURRENTHOST=$(hostname)
echo "CURRENTHOST : $CURRENTHOST"

if [[ $CURRENTHOST != busd-api* ]]; then
    echo "CANCELED"
    echo "  You are trying to run the script on $CURRENTHOST"
    echo "  THIS SCRIPT SHOULD ONLY BE USED ON THE API-SERVER"
fi
# Change the current directory to the script directory
BASEDIR=$(dirname "$0")
cd $BASEDIR
# Look for the .env file
while [[ "$PWD" != "$HOME" && ! -e .env ]]; do cd ..; done
if [[ -e .env ]]; then
  ENVFILEDIR=$PWD
  set -a; source .env; set +a
  echo "Using .env file found in $PWD"
else
  echo "CANCELED"
  echo "  No .env file found in the directory tree."
  echo "  Please setup the .env file and retry"
fi
# Change the current directory to the parent of the home directory
cd $INFAMOUSDIR
echo "EXECUTED FROM $PWD"
# Check if the correct number of arguments is provided
if (($# != 2))
then
    echo " "
    echo "CANCELED"
    echo "  Wrong number of arguments : $# were provided but 2 are expected (version_number/branch_name and github_token)"
    echo "  Syntax : ./tools/release_on_apiserver.sh version_number github_token"
    echo "  or"
    echo "  Syntax : ./tools/release_on_apiserver.sh branch_name github_token"
    echo "  Examples:"
    echo "      To release the v1.0.0 :"
    echo "      ./tools/release_on_apiserver.sh v1.0.0 YOUR_GITHUB_TOKEN"
    echo "      or"
    echo "      To release the current version of the branch foobar:"
    echo "      ./tools/release_on_apiserver.sh foobar YOUR_GITHUB_TOKEN"
    exit
fi

# Set github token on the server
echo " "
echo "SETTING GITHUB TOKEN ON THE API-SERVER"
echo "https://$2:x-oauth-basic@github.com" >> ~/.git-credentials

echo " "
echo "RETRIEVING SPECIFIED VERSION/BRANCH"
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
if [[ $CURRENT_BRANCH == $1 ]]; 
then
    echo "  The current branch is already $1, just fetch/pull it"
    git fetch
    git pull
else
    echo "  The release branch $1 is different from the current branch $CURRENT_BRANCH, we'll replace it with the new branch"
  git fetch origin $1
  git checkout FETCH_HEAD -b $1
  git branch -D $CURRENT_BRANCH
fi

echo " "
echo "DELETING GITHUB TOKEN FROM THE API-SERVER"
rm  ~/.git-credentials

echo " "
echo "RELEASE DONE"