#!/usr/bin/bash

# update for nodejs
# APP:

# usage 
# for private cloud: updateApp.sh -appDir /epm2_app -uploadDir /upload/sys

# for test env: updateApp.sh -uploadDir /data_disk/UPLOAD/sys -procName leoncons
#set -x

dateStr=`date '+%Y%m%d-%H%M%S'`
echo "update epm app $dateStr"

base_dir=`pwd`
echo $base_dir

#appTargetDir='/home/epm'
while [ $# -gt 0 ]; do
  COMMAND=$1
  case $COMMAND in
    -appDir)
      appDir=$2
      shift 2
      ;;
    -uploadDir)
      uploadDir=$2
      shift 2
      ;;
    -procName)
      procName=$2
      shift 2
      ;;
    *)
      break
      ;;
  esac
done

if [[ $appDir = '' ]];then
  appDir="/data_disk/APP/${procName}"
fi
webPm2Name="${procName}_backend"
etlPm2Name="${procName}_etl_worker"
devPm2Name="${procName}_dev"

echo "appDir:$appDir,  uploadDir:$uploadDir, webPm2Name:$webPm2Name, etlPm2Name:$etlPm2Name, devPm2Name:$devPm2Name"

cd $uploadDir
appTarfile=`ls -ltr | tail -1 | awk '{print $9}'`
echo "appTarfile $appTarfile"

if [[ $appTarfile ]];then
   echo "update app"
   cd $appDir

   echo "tar zxf $uploadDir/$appTarfile"
   tar zxf $uploadDir/$appTarfile
   if [[ $webPm2Name ]];then
     mv backend.js ${webPm2Name}.js
     pm2 reload ${webPm2Name} --force
   fi
   if [[ $etlPm2Name ]];then
     mv etl_worker.js ${etlPm2Name}.js
     pm2 reload ${etlPm2Name} --force
   fi
   if [[ $devPm2Name ]];then
     mv dev.js ${devPm2Name}.js
     pm2 reload ${devPm2Name} --force
   fi
   
   echo 'app update done'
else
   echo 'build not exist'
fi

exit 0