#!/usr/bin/bash
#use root
# ./pm2 -installPath xxx/EPM2

#pridev:
# ./pm2 -installPath /data_disk/EPM2
set -x
echo "install nodejs pm2"
baseDir=`pwd`
echo $baseDir

installPath='/EPM2'
while [ $# -gt 0 ]; do
  COMMAND=$1
  case $COMMAND in
    -installPath)
      installPath=$2
      shift 2
      ;;
    -nodeBin)
        nodeBin=$2
        shift 2
        ;;
    *)
      break
      ;;
  esac
done
appDir="$installPath/APP"
if test -e $installPath
then
    echo "data dir exist: $installPath"
else
    echo "data dir does not exist, create it: $installPath"
    mkdir $installPath
fi

#clean
rm -rf $installPath/NODE

#http://tool.epm2demo.cn/nodeinstall/node-v16.20.2-linux-x64.tar.gz
#http://tool.epm2demo.cn/nodeinstall/logrotate.tar
client='node-v16.20.2-linux-x64.tar.gz'
if test -e $client
then
    echo "client exist: $client"
else
    echo "client does not exist, get it: $client"
    wget http://tool.epm2demo.cn/nodeinstall/node-v16.20.2-linux-x64.tar.gz
fi
tar zxf $baseDir/node-v16.20.2-linux-x64.tar.gz -C $installPath
cd $installPath
mv node-v16.20.2-linux-x64 NODE 

cd $baseDir
client='pm2.tar'
if test -e $client
then
    echo "client exist: $client"
else
    echo "client does not exist, get it: $client"
    wget http://tool.epm2demo.cn/nodeinstall/$client
fi
tar zxf $baseDir/$client -C $installPath/NODE/lib/node_modules

ln -sf $installPath/NODE/bin/node $nodeBin/node
ln -sf $installPath/NODE/bin/npm $nodeBin/npm
ln -sf $installPath/NODE/lib/node_modules/pm2/bin/pm2 $nodeBin/pm2

pm2 del all
pm2 update

#log clear
cd $baseDir
client='logrotate.tar'
if test -e $client
then
    echo "client exist: $client"
else
    echo "client does not exist, get it: $client"
    wget http://tool.epm2demo.cn/nodeinstall/$client
fi
tar zxf $client
cd pm2-logrotate/node_modules/pm2-logrotate/
pm2 install .
pm2 set pm2-logrotate:max_size 100M
pm2 set pm2-logrotate:retain 50
pm2 set pm2-logrotate:compress false
pm2 set pm2-logrotate:workerInterval 300

nodeV=`node -v`
npmV=`npm -v`
pm2V=`pm2 -v`
if [ $nodeV = "v16.20.2" -a $npmV = "8.19.4" -a $pm2V = "5.1.0" ];then
  echo 'install success'
else
  echo 'install fail'
  exit 1
fi