#!/bin/bash +x

set -e
set -x

RELEASE=${1:-1.0.0}

mkdir $RELEASE -p

pushd $RELEASE

echo "[Info] create folder ${RELEASE} "


CORE_REPOS=("on-core" "on-tasks" "di.js" )
OTHER_REPOS=("on-http" "on-taskgraph" "on-dhcp-proxy" "on-tftp" "on-syslog" )
REPOS=("${CORE_REPOS[@]}" "${OTHER_REPOS[@]}" )
#GITHUB="https://eos2git.cec.lab.emc.com/RackHD" # https://github.com/RackHD
GITHUB="https://github.com/RackHD"

GIT_REFSPEC="release/${RELEASE}"

echo "[Info] Clone RackHD repos, and checkout to tag ${GIT_REFSPEC}"


for r in ${REPOS[@]}; do
    rm ${r} -rf
    git clone ${GITHUB}/${r}.git
    pushd ${r}
    git fetch --all --tags
    git checkout ${GIT_REFSPEC}
    npm install --production
    popd 
done

echo "[Info] Move the on-core/on-tasks into each dependent repo's node_modueles..."

for r in ${OTHER_REPOS[@]}; do
    pushd ${r}/node_modules/
    #remove the on-core/on-tasks, and replace by a link to local folder
    for dep in ${CORE_REPOS[@]}; do
       rm ${dep} -rf
       ln -s ../../${dep}     ${dep}
    done
    popd
done

echo "[Info] npm install pm2...."

sudo npm install -g pm2

echo  "
apps:
  - script: index.js
    name: on-taskgraph
    cwd: on-taskgraph
  - script: index.js
    name: on-http
    cwd: on-http
  - script: index.js
    name: on-dhcp
    cwd: on-dhcp-proxy
  - script: index.js
    name: on-syslog
    cwd: on-syslog
  - script: index.js
    name: on-tftp
    cwd: on-tftp
" > rackhd-pm2-config.yml

echo "[Info] Starts RackHD with pm2"

sudo pm2 start rackhd-pm2-config.yml

popd

