#!/usr/bin/bash
#use non root/root
# can replace existing pm2
#pridev:
# ./pm2.sh -installPath /data_disk/EPM2 -nodeBin /home/epm/bin
set -x
# set -xe
# if use -e, normal process can not proceed
echo "install nodejs pm2"
baseDir=`pwd`
echo $baseDir

nodeBin='/home/epm/bin'
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 -p $installPath
fi

#clean
rm -rf $installPath/NODE

#http://tool.epm2demo.cn/nodeinstall/node-v20.11.0-linux-x64.tar.gz
#http://tool.epm2demo.cn/nodeinstall/logrotate.tar
client='node-v20.11.0-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-v20.11.0-linux-x64.tar.gz
fi
tar zxf $baseDir/node-v20.11.0-linux-x64.tar.gz -C $installPath
cd $installPath
mv node-v20.11.0-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 = "v20.11.0" -a $npmV = "10.2.4" -a $pm2V = "5.1.0" ];then
  echo 'install success'
else
  echo 'install fail'
  exit 1
fi

cd $baseDir
client='mongodb-linux-x86_64-enterprise-rhel80-4.2.23'
echo 'install mongo tool'
if test -e $client.tgz
then
    echo "client exist: $client"
else
    echo "client does not exist, get it: $client"
    wget http://tool.epm2demo.cn/mongo/private/$client.tgz
fi

tar zxf $client.tgz -C $installPath/MONGO
ln -sf $installPath/MONGO/$client/bin/mongo /usr/bin/mongo
ln -sf $installPath/MONGO/$client/bin/mongodump /usr/bin/mongodump
ln -sf $installPath/MONGO/$client/bin/mongorestore /usr/bin/mongorestore