#!/usr/bin/bash

#pre: yum install -y nc

# ./mongoInstall.sh -installPath /EPM2 -hanaHost xxxx
# install to /EPM2/MONGO

#pridev
# # ./install.sh -installPath /data_disk/EPM2 -hanaHost 192.168.124.248

#set -x
echo "install mongo"
baseDir=`pwd`
echo $baseDir

installPath='~/EPM2'
imageV='keyfunc.tencentcloudcr.com/prod/mongo-enterprise:v5.0.24'
while [ $# -gt 0 ]; do
  COMMAND=$1
  case $COMMAND in
    -hanaHost)
      hanaHost=$2
      shift 2
      ;;
    -installPath)
      installPath=$2
      shift 2
      ;;
    *)
      break
      ;;
  esac
done

if test -e $installPath
then
    echo "data dir exist: $installPath"
else
    echo "data dir does not exist, create it: $installPath"
    mkdir $installPath
fi

#clean
mongoPath=$installPath/MONGO
rm -rf $mongoPath
mkdir -p $mongoPath/BACKUP $mongoPath/EXPORT $mongoPath/data $mongoPath/logs
chmod -R 777 $mongoPath
chmod -R 777 $mongoPath/BACKUP
cp mongod.conf $mongoPath

imageExist=`docker images | grep 'mongo'`
if [[ $imageExist ]]; then
   echo 'imageExist'
else
   echo 'image not Exist, load image'
   docker load < mongoImageV5.tar
fi

dockerid=`docker ps -a | tail -n+2 | grep mongo | awk '{print $1}'`
echo "docker to rm $dockerid"
if [ $dockerid ];then 
  docker stop $dockerid
  docker rm $dockerid
  echo "docker del done"
fi
echo "start docker"
docker run --restart unless-stopped --name mongo -d -p 27017:27017 -v $mongoPath:/etc/mongo -v $mongoPath:/tmp -v $mongoPath/data:/var/lib/mongodb -v $mongoPath/logs:/var/log/mongodb $imageV --config /etc/mongo/mongod.conf

until nc -z 127.0.0.1 27017
do
   sleep 1
done

echo 'mongo started'

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

tar zxf mongosh-1.10.3-linux-x64.tgz -C $installPath/MONGO
ln -sf $installPath/MONGO/mongosh-1.10.3-linux-x64/bin/mongosh /usr/bin/mongosh
echo 'init db'
mongosh 127.0.0.1 initDb.js EPM $hanaHost

echo 'install mongo tool'
cd $baseDir
client='mongodb-linux-x86_64-enterprise-rhel80-4.2.23'
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

echo 'finish'