#!/bin/bash
set -e
#echo "[`date +'%F %H:%M:%S'`] [INFO] useage : sh install_mdd.sh [setup_mode] [local_ip] [mdd_vip]"

if [ $# -ne 3 ]; then
    echo "$(basename $0): Missing script argument"
    echo "$(basename $0) [setup_mode] [local_ip] [mdd_vip]"
    exit 1
fi

pd=$PWD
setup_mode=$1
IP=$2
VIP=$3
set +e
source /etc/profile
set -e
#export JAVA_HOME=$JAVA_HOME
#export PATH=$PATH:$JAVA_HOME/bin

## install mdd ##
if [ -z "$JAVA_HOME" ];then
    echo "jdk not be installed,please install jdk first!"
    exit 1
fi

mkdir -p olapserver && unzip -o bos-olap-setup.zip  -d olapserver > /dev/null 2>&1
mkdir -p $pd/olapserver/redo && mkdir -p $pd/olapserver/backup
chmod -R 755 $pd/
chmod +x $pd/olapserver/bin/start.sh

# 调整启动参数，适配arm64操作系统
arch=`arch`
if [[ ${arch} = "aarch64" ]];then
  sed -i 's/nohup  java -Duser/nohup  java -DEnableMddOtherCpu=true -Duser/g' $pd/olapserver/bin/start.sh
fi

redo=$pd/olapserver/redo
backup=$pd/olapserver/backup

if [ $setup_mode -eq "1" ];then
   cp -rf replication_master.xml  $pd/olapserver/conf/replication.xml
   sed -i s/mdd_vip/$VIP/g $pd/olapserver/conf/replication.xml
   sed -i s/host_ip/$IP/g  $pd/olapserver/conf/replication.xml
   sed -i "s:redo_dir:$redo:g" $pd/olapserver/conf/replication.xml
   sed -i "s:backup_dir:$backup:g" $pd/olapserver/conf/replication.xml

else
   cp -rf replication_slave.xml  $pd/olapserver/conf/replication.xml
   sed -i s/mdd_vip/$VIP/g $pd/olapserver/conf/replication.xml
   sed -i s/host_ip/$IP/g  $pd/olapserver/conf/replication.xml
   sed -i "s:redo_dir:$redo:g" $pd/olapserver/conf/replication.xml
   sed -i "s:backup_dir:$backup:g" $pd/olapserver/conf/replication.xml
fi

## register systemd ##
cat > /usr/lib/systemd/system/mdd.service <<EOF
[Unit]
Description=mdd
After=syslog.target network.target

[Service]
Type=forking
Environment="JAVA_HOME=$JAVA_HOME"
Environment="PATH=$PATH:$JAVA_HOME/bin"
ExecStart=$pd/olapserver/bin/start.sh start
ExecStop=$pd/olapserver/bin/start.sh stop

[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl start mdd
systemctl enable mdd

## echo install resault ##
portOK=`netstat -ntpl|grep "\<8080\>" || true`
if [[ -z $portOK ]];then
    echo "mdd install failed!"
else
    echo "mdd install susses!"
fi




 
