######################################################################
####function: install mc
####author:danial_chen
####create date:2020-03
####modify date:2020-03
######################################################################

#!/bin/bash
set -e
echo "[$(date +'%F %H:%M:%S')] [INFO] useage :  sh installmc.sh clustername zkconfig nginx_vip environment_type"
if [ $# -ne 7 ]; then
  echo "$(basename $0): Missing script argument"
  echo "$(basename $0) [clustername] [zkconfig] [nginx_vip] [environment_type] [redis_cache_config] [redis_session_config] [monitor_es_url]"
  exit
fi

pd=$PWD
## update config ##
clustername=$1
zkconfig=$2
nginx_vip=$3
environment_type=$4
redis_cache_config=$(echo $5 | sed 's#\&#\\&#g')
redis_session_config=$(echo $6 | sed 's#\&#\\&#g')
monitor_es_url=$7

# 替换资源值
Xms_config="-Xms3072m"
Xmx_config="-Xmx3072m"
limits_cpu="2"
limits_memory="5Gi"
requests_cpu="2"
requests_memory="5Gi"
if [ "$environment_type" != "prod" ]; then
  Xms_config="-Xms1024m"
  Xmx_config="-Xmx1024m"
  limits_cpu="500m"
  limits_memory="2Gi"
  requests_cpu="500m"
  requests_memory="2Gi"
fi
sed -i s/Xms_config/$Xms_config/g $pd/mc/mc.yaml
sed -i s/Xmx_config/$Xmx_config/g $pd/mc/mc.yaml
sed -i s/limits_cpu/$limits_cpu/g $pd/mc/mc.yaml
sed -i s/limits_memory/$limits_memory/g $pd/mc/mc.yaml
sed -i s/requests_cpu/$requests_cpu/g $pd/mc/mc.yaml
sed -i s/requests_memory/$requests_memory/g $pd/mc/mc.yaml

#update setappenv
sed -i s/clustername/$clustername/g $pd/mc/mc.yaml
sed -i s/clustername/$clustername/g $pd/mc/mc-svc.yaml
sed -i s/zkconfig/$zkconfig/g $pd/mc/mc.yaml
sed -i s/nginx_vip/$nginx_vip/g $pd/mc/mc.yaml
sed -i "s#redis_cache_config#$redis_cache_config#g" $pd/mc/mc.yaml
sed -i "s#redis_session_config#$redis_session_config#g" $pd/mc/mc.yaml
sed -i "s#monitor_es_url#$monitor_es_url#g" $pd/mc/mc.yaml
# update label for gpaas
sed -i "s/cluster:.*/cluster: cosmic_$clustername/g" $pd/mc/*.yaml

#create namespaces
ns=$(kubectl get ns | grep $clustername | wc -l)
if [ $ns -eq 0 ]; then
  kubectl create ns $clustername
fi

#create mc service
cd $pd/mc
kubectl apply -f .

echo "mc install success!"
