######################################################################
####function: install nginx
####author:lance_cao
####create date:2019-11
####modify date:2019-11
######################################################################

#!/bin/bash
nginx_version="nginx-1.22.0"
set -e
echo "[$(date +'%F %H:%M:%S')] [INFO] useage :  sh installngnix.sh [mservicehosts] [mchosts] [fileserverhosts] [mservice_isk8s] [fileserver_isk8s] [ierpport] [tenantid] [mqhosts] [mddhost] [k8ehost] [k8smasterhosts] [k8s_vip] [mdd_vip] [os]"

if [ $# -ne 14 ]; then
  echo "$(basename $0): Missing script argument"
  echo "$(basename $0) [mservicehosts] [mchosts] [fileserverhosts] [mservice_isk8s] [fileserver_isk8s] [ierpport] [tenantid] [mqhosts] [mddhost] [k8ehost] [k8smasterhosts] [k8s_vip] [mdd_vip] [os]"
  exit 1
fi
pd=$PWD
echo "pwd: $pd"
cd ../../nginx-logs
nginx_logs=$PWD

os=${14}
# 判断系统
test -z ${os} && echo "操作系统为空" && exit 1

if [[ ${os} == "ubuntu" ]]; then
  if [ ! -L /usr/lib/libssl.so.1.1 ]; then
    ln -s /usr/lib/x86_64-linux-gnu/libssl.so /usr/lib/libssl.so.1.1
  fi
  if [ ! -L /usr/lib/libcrypto.so.1.1 ]; then
    ln -s /usr/lib/x86_64-linux-gnu/libcrypto.so /usr/lib/libcrypto.so.1.1
  fi
else
  echo "其他操作系统无需单独处理"
fi

cd $pd
## setup nginx ##
# yum install gcc  gcc-c++ zlib unzip  openssl openssl-devel   -y

tar -xf ${nginx_version}-${os}.tar.gz
rm -rf /usr/local/nginx && mv -f $pd/nginx /usr/local/

#rm -rf nginx_upstream_check_module-master
#tar -xf nginx-1.22.0.tar.gz
#rm -rf pcre-8.34
#unzip nginx_upstream_check_module-master.zip
#unzip pcre-8.34.zip
#tar -xf zlib-1.2.11.tar.gz
#
#cd $pd/zlib-1.2.11
#./configure
#make && make install
#
#cd $pd/$nginx_version
#./configure --prefix=/usr/local/nginx --with-http_ssl_module --with-http_gunzip_module --add-module=$pd/nginx_upstream_check_module-master --with-pcre=$pd/pcre-8.34 --with-stream --with-ipv6
#make && make install

## update config ##
mservicehosts=($1) #k8s servers or cosmic server
mchosts=($2)
fileserverhosts=($3)
mservice_isk8s=$4
fileserver_isk8s=$5
ierpport=$6
tenantid=$7
#mqhosts=($8)
mqhosts=($(echo $8 | sed 's/,/ /g'))
mddhost=$9
k8ehost=${10}
k8smasterhosts=(${11})
k8svip=${12}
mddvip=${13}

if [ $mservice_isk8s -eq 1 ]; then #容器方式
  \cp -rf $pd/conf/conf.d/upstream.conf-k8s $pd/conf/conf.d/upstream.conf
  svr_mcport=30001
  svr_ierpport=30002
else #非容器方式
  \cp -rf $pd/conf/conf.d/upstream.conf-one $pd/conf/conf.d/upstream.conf
  svr_mcport=8082
  svr_ierpport=8080
fi

if [ $fileserver_isk8s -eq 1 ]; then #容器方式
  svr_fileserverport=30003
else #非容器方式
  svr_fileserverport=8100
fi

sed -i s/ierp_port/"$ierpport"/g ./conf/conf.d/ierp.conf
sed -i s/tenant_id/"$tenantid"/g ./conf/conf.d/ierp.conf

sed -i s@/usr/local/nginx/logs@$nginx_logs@g ./conf/conf.d/ierp.conf
sed -i s@/usr/local/nginx/logs@$nginx_logs@g ./conf/conf.d/mc.conf

# 处理mdd参数
mddipport=(${mddhost//:/ })
if [ -n "$mddvip" ]; then
  mddip=$mddvip
else
  mddip=${mddipport[0]}
fi
mddport=${mddipport[1]:-8080}
sed -i s/mdd-ip/$mddip/g ./conf/conf.d/upstream.conf
sed -i s/mdd-port/$mddport/g ./conf/conf.d/upstream.conf

sed -i s/k8e-ip/$k8ehost/g ./conf/conf.d/upstream.conf

if [ -n "$k8svip" ]; then
  sed -i "/next-ierp/a\\    server $k8svip:$svr_ierpport;" ./conf/conf.d/upstream.conf
  sed -i s@svr_ierpport@$svr_ierpport@g ./conf/conf.d/upstream.conf
  sed -i "/next-mc/a\\    server $k8svip:$svr_mcport;" ./conf/conf.d/upstream.conf
  sed -i s@svr_mcport@$svr_mcport@g ./conf/conf.d/upstream.conf
  sed -i "/next-fileserver/a\\    server $k8svip:$svr_fileserverport;" ./conf/conf.d/upstream.conf
  sed -i s@svr_fileserverport@$svr_fileserverport@g ./conf/conf.d/upstream.conf
else
  for ((i = ${#mservicehosts[@]} - 1; i >= 0; i--)); do
    sed -i "/next-ierp/a\\    server ${mservicehosts[$i]}:$svr_ierpport;" ./conf/conf.d/upstream.conf
    sed -i s@svr_ierpport@$svr_ierpport@g ./conf/conf.d/upstream.conf
  done
  for ((i = ${#mchosts[@]} - 1; i >= 0; i--)); do
    sed -i "/next-mc/a\\    server ${mchosts[$i]}:$svr_mcport;" ./conf/conf.d/upstream.conf
    sed -i s@svr_mcport@$svr_mcport@g ./conf/conf.d/upstream.conf
  done
  for ((i = ${#fileserverhosts[@]} - 1; i >= 0; i--)); do
    sed -i "/next-fileserver/a\\    server ${fileserverhosts[$i]}:$svr_fileserverport;" ./conf/conf.d/upstream.conf
    sed -i s@svr_fileserverport@$svr_fileserverport@g ./conf/conf.d/upstream.conf
  done
fi

# sed -i s/mqhost-vip/${mqhosts[0]}/g ./conf/conf.d/upstream.conf
# if mq is cluster then manager use master-backup
# nginx代理的是rabbitmq的管理界面端口
for ((i = ${#mqhosts[@]} - 1; i >= 0; i--)); do
  temp=${mqhosts[$i]}
  ipport=(${temp//:/ })
  ip=${ipport[0]}
  port=${ipport[1]:-15672}
  if [ $i -eq 0 ]; then
    sed -i "/mqserver/a\\    server ${ip}:15672;" ./conf/conf.d/upstream.conf
  elif [ $i -eq 1 ]; then
    sed -i "/mqserver/a\\    server ${ip}:15672 backup;" ./conf/conf.d/upstream.conf
  fi
done

cp -rf ./next.conf.template ./conf/next.conf
len=${#mqhosts[@]}
if [ $len -gt 1 ]; then ##insert mq LB
  sed -i "/stream {/a\\    upstream mq_server{" ./conf/next.conf
  for ((i = ${#mqhosts[@]} - 1; i >= 0; i--)); do
    temp=${mqhosts[$i]}
    ipport=(${temp//:/ })
    ip=${ipport[0]}
    port=${ipport[1]:-5672}
    sed -i "/upstream mq_server{/a\\        server ${ip}:${port} max_fails=2 fail_timeout=10s;" ./conf/next.conf
  done
  temp=${mqhosts[$len - 1]}
  ipport=(${temp//:/ })
  ip=${ipport[0]}
  port=${ipport[1]:-5672}
  sed -i "/server ${ip}:${port} max_fails=2 fail_timeout=10s;/a\\    } \n    server { \n        listen  5671 so_keepalive=on;\n        proxy_connect_timeout 300s; \n        proxy_timeout 300s; \n        proxy_pass mq_server;\n    }" ./conf/next.conf
fi

# nginx 7443负载3台k8s master的6443 没用到，先注释掉
#len=${#k8smasterhosts[@]}
#if [ $len -gt 1 ]; then ##insert mq LB
#  sed -i "/stream {/a\\    upstream ierp_cloud{" ./conf/next.conf
#  for ((i = ${#k8smasterhosts[@]} - 1; i >= 0; i--)); do
#    sed -i "/upstream ierp_cloud{/a\\        server ${k8smasterhosts[$i]}:6443 max_fails=2 fail_timeout=10s;" ./conf/next.conf
#  done
#  sed -i "/server ${k8smasterhosts[$len - 1]}:6443 max_fails=2 fail_timeout=10s;/a\\    } \n    server { \n        listen  7443 so_keepalive=on;\n        proxy_connect_timeout 300s; \n        proxy_timeout 300s; \n        proxy_pass ierp_cloud;\n    }" ./conf/next.conf
#fi

mkdir -p /usr/local/nginx/conf/conf.d
cp -rf ./conf/next.conf /usr/local/nginx/conf/nginx.conf
cp -rf ./conf/conf.d/* /usr/local/nginx/conf/conf.d/
## nginx和mq同一台主机不需要该配置文件
if [ $(ss -tunlp | grep ':15672 ' | wc -l) != 0 ]; then
  rm -rf /usr/local/nginx/conf/conf.d/mq.conf
fi

## Register to system service  ##
cat > /usr/lib/systemd/system/nginx.service << EOF
[Unit]
Description=The nginx HTTP and reverse proxy server
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
ExecStartPre=/usr/local/nginx/sbin/nginx -t
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/bin/kill -s HUP \$MAINPID
ExecStop=/bin/kill -s QUIT \$MAINPID
PrivateTmp=true
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl restart nginx
systemctl enable nginx

echo "NGINX install success "

# openEuler kylin SP3 20240426 加密算法比较特殊，需要机上mc适配的加密算法，否则初始化的时候mc连接不上
if grep 'HostKeyAlgorithms ssh-ed25519,ssh-ed25519-cert-v01@openssh.com,rsa-sha2-256,rsa-sha2-512' /etc/ssh/sshd_config; then
  # 定义要检查的算法
  key_algorithms=("ssh-rsa" "ssh-dss" "ecdsa-sha2-nistp256-cert-v01@openssh.com" "ecdsa-sha2-nistp384-cert-v01@openssh.com" "ecdsa-sha2-nistp521-cert-v01@openssh.com")

  # sshd_config 文件路径
  SSHD_CONFIG="/etc/ssh/sshd_config"

  # 检查并添加算法
  for algo in "${key_algorithms[@]}"; do
    if ! grep -q "^HostKeyAlgorithms.*$algo" "$SSHD_CONFIG"; then
      if grep -q "^HostKeyAlgorithms" "$SSHD_CONFIG"; then
        sed -i "/^HostKeyAlgorithms/s/$/,$algo/" "$SSHD_CONFIG"
      else
        echo "HostKeyAlgorithms $algo" >> "$SSHD_CONFIG"
      fi
      echo "Added $algo to HostKeyAlgorithms"
    else
      echo "$algo already exists in HostKeyAlgorithms"
    fi
  done

  # 重启 SSH 服务以应用更改
  systemctl restart sshd

  echo "SSH service restarted to apply changes."
fi
