######################################################################
#### function: Initialize system parameters
####author:danial_chen
####create date:2019-11-07
####modify date:2019-11-07
######################################################################
#/bin/bash
#useage: sh init_sys_parm.sh
set -e
pd=$PWD

systemd_var='
#####cosmicval 
DefaultLimitCORE=infinity
DefaultLimitNOFILE=655350
DefaultLimitNPROC=655350
'
if [ $(grep cosmicval /etc/systemd/system.conf | wc -l) = 0 ]; then
  echo "$systemd_var" >> /etc/systemd/system.conf
  systemctl daemon-reexec
fi

## edit /etc/sysctl.conf ##
# net.ipv4.tcp_tw_recycle 存在改为0 不存在就不添加
declare -A sysctl_conf
sysctl_conf["vm.overcommit_memory"]="1"
sysctl_conf["vm.max_map_count"]="1048576"
sysctl_conf["kernel.shmall"]="2043878"
sysctl_conf["kernel.shmmax"]="8175512"
sysctl_conf["kernel.shmmni"]="4096"
sysctl_conf["kernel.sem"]="5010 1048576 5010 4096"
sysctl_conf["fs.file-max"]="6553560"
sysctl_conf["fs.aio-max-nr"]="2097152"
sysctl_conf["net.ipv4.ip_local_port_range"]="1024 65000"
sysctl_conf["net.core.rmem_default"]="262144"
sysctl_conf["net.core.rmem_max"]="262144"
sysctl_conf["net.core.somaxconn"]="2048"
sysctl_conf["net.core.wmem_default"]="262144"
sysctl_conf["net.core.wmem_max"]="262144"
sysctl_conf["net.ipv4.tcp_tw_recycle"]="0"
sysctl_conf["net.ipv4.tcp_rmem"]="262144"
sysctl_conf["net.ipv4.tcp_wmem"]="262144"
for key in "${!sysctl_conf[@]}"; do
  value="${sysctl_conf[$key]}"
  if [ $(grep "$key" /etc/sysctl.conf | wc -l) != 0 ]; then
    sed -i "s/^$key.*/$key = $value/" /etc/sysctl.conf
  elif [ "$key" != "net.ipv4.tcp_tw_recycle" ]; then
    echo "$key = $value" >> /etc/sysctl.conf
  fi
done

## ulimit settings ##
declare -a limits_conf=("* soft nofile 1048576" "* hard nofile 1048576" "* soft nproc 1048576" "* hard nproc 1048576")
for value in "${limits_conf[@]}"; do
  if [ $(grep "$value" /etc/security/limits.conf | wc -l) = 0 ]; then
    echo "$value" >> /etc/security/limits.conf
  fi
done

sysctl -p || echo


## echo install resault ##
echo "System parameters init success!"
