#!/bin/bash
# for not SUSE os, need to alter docker container_id & pm2 dir
# usage
# ./restart.sh

DATE=`date`
echo $DATE >> restart_daily.log
echo $DATE
echo "restart mongo" >> restart_daily.log && systemctl restart mongod.service &
echo "restart mongo"
PID1=$!
STATUS1=`systemctl status mongod.service | grep inactive -c`
while [[ $STATUS1 = 1 ]]
do
  sleep 5
  STATUS1=`systemctl status mongod.service | grep inactive -c`
done

echo "restart docker" >> restart_daily.log && systemctl restart docker.service &
echo "restart docker"
PID2=$!
STATUS2=`systemctl status docker.service | grep inactive -c`
while [[ $STATUS2 = 1 ]]
do
  sleep 5
  STATUS2=`systemctl status docker.service | grep inactive -c`
done

wait $PID1
wait $PID2
echo "restart hana" >> restart_daily.log && docker restart 4d500e027d22 &
echo "restart hana"
PID3=$!

wait $PID3
STATUS3=`docker ps | grep healthy -c`
while [[ $STATUS3 = 0 ]]
do
  sleep 5
  STATUS3=`docker ps | grep healthy -c`
done

wait $PID3
echo "restart pm2" >> restart_daily.log && pm2 reload all &
echo "restart pm2"
PID4=$!
RESULT_PM2=$?
  
wait $PID4
if [[ $RESULT_PM2 = 0 ]]; then
  echo "pm2 restart successfully!" >> restart_daily.log
  echo "pm2 restart successfully!"
else
  if [[ $RESULT_BACKEND -ne 4 ]]; then
    echo "backend restart failed!" >> restart_daily.log
	echo "backend restart failed!"
  elif [[ $RESULT_ETL_WORKER -ne 1 ]]; then
    echo "etl_worker restart failed!" >> restart_daily.log
	echo "etl_worker restart failed!"
  else
    echo "backend and etl_worker restart successfully!" >> restart_daily.log
	echo "backend and etl_worker restart successfully!"
  fi
  cd /home/PRD/epm2_app
  pm2 delete all &
  wait $!
  pm2 start backend.js -i 4 --merge-logs &
  wait $!
  RESULT_BACKEND=`pm2 list | grep backend -c`
  pm2 start etl_worker.js &
  wait $!
  RESULT_ETL_WORKER=`pm2 list | grep etl_worker -c`
  if [[ $RESULT_BACKEND -ne 4 ]]; then
    echo "backend restart failed!" >> restart_daily.log
	echo "backend restart failed!"
  elif [[ $RESULT_ETL_WORKER -ne 1 ]]; then
    echo "etl_worker restart failed!" >> restart_daily.log
	echo "etl_worker restart failed!"
  else
    echo "backend and etl_worker restart successfully!" >> restart_daily.log
	echo "backend and etl_worker restart successfully!"
  fi 
fi

echo "-------------------------------------------------------------------------------" >> restart_daily.log
