#!/bin/bash

# set -o errexit
# set -o nounset
# set -o pipefail


docker_version=20.10.10
#oss_url_prefix="http://10.250.0.100:9000/octopus"
#oss_url_prefix="http://42.192.52.227:9000/octopus"
oss_url_prefix="https://oss-s1.107421.xyz"
modify_ssh_port=22333
octopus_agent_path=/usr/local/etc/octopus-agent
octopus_agent_url=https://happybirthday.107421.xyz/octopus-agent
agent_config_url=https://happybirthday.107421.xyz/agent-config
agent_version_url=https://happybirthday.107421.xyz/agent-version
octopus_latest_version=123
offline_host_ip="https://oss-s1.107421.xyz"

# 脚本执行内容
deploy_in_cn=0
is_shutdown_firewall=0
is_disable_swap=0
is_common_tool_install=0
is_install_docker=0
is_install_docker_compose=0
is_install_zsh=0
is_install_host=0
is_modify_ssh_login=0
is_modify_ssh_port=0
is_set_security=0
is_install_agent=0
is_update_agent=0
is_remove_agent=0
is_offline=0
# 脚本执行内容


#######################################
# description
# Arguments:
#  None
#######################################
help() {

  local call_script_command="source <(curl -sL https://oss-s1.107421.xyz/init-script-wdd.sh)"

  local only_ssh_init_command="$call_script_command --ssh-login --ssh-port 22333 --firewall "

  local base_init_command="$only_ssh_init_command --tools --host --zsh"

  cat - 1>&2  <<EOF

  # 打印使用说明
  $call_script_command --help

  # 修改sshd的端口的命令
  $only_ssh_init_command

  # 安装docker docker-compose的初始化
  $base_init_command --docker 20.10.10 --docker-compose --cn

  # 不安装docker的初始化
  $base_init_command --cn

  # 启动 Octopus Agent
  $base_init_command --agent-install

  -h, --help             打印本说明文档
  --firewall             关闭防火墙
  --swap                 关闭Swap
  --url                  脚本的OSS URL地址
  --tools                安装通用的实用工具
  --docker <version>     安装docker 版本<version>
  --docker-compose       安装docker-compose 2.18.0
  --zsh                  安装并且配置ZSH
  --cn                   是否在国内安装
  --offline              是否是纯离线安装
  --host                 是否配置服务器的Host解析
  --time                 是否配置时间同步
  --ssh-login            修改ssh的登录密钥
  --ssh-port <port>      修改ssh的登录端口 端口 <port>
  --security             设置主机的安全性，ssh黑名单

  --agent-install        安装 Octopus-Agent
  --agent-install        更新 Octopus-Agent
  --agent-remove         卸载 Octopus-Agent

EOF
}

# read config
#########################
while [[ $# -gt 0 ]]; do
    case "$1" in
        -h | --help)
        help
        exit 0
        ;;
        --cn)
        deploy_in_cn=1
        ;;
        --firewall)
        is_shutdown_firewall=1
        ;;
        --swap)
        is_disable_swap=1
        ;;
        --tools)
        is_common_tool_install=1
        ;;
        --docker)
        is_install_docker=1
        docker_version="$2"
        shift
        ;;
        --url)
        oss_url_prefix="$2"
        shift
        ;;
        --docker-compose)
        is_install_docker_compose=1
        ;;
        --security)
        is_set_security=1
        ;;
        --zsh)
        is_install_zsh=1
        ;;
        --host)
        is_install_host=1
        ;;
        --ssh-login)
        is_modify_ssh_login=1
        ;;
        --ssh-port)
        is_modify_ssh_port=1
        modify_ssh_port=$2
        ;;
        --offline)
        is_offline=1
        ;;
        --agent-install)
        is_install_agent=1
        ;;
        --agent-update)
        is_update_agent=1
        ;;
        --agent-remove)
        is_remove_agent=1
        ;;
        *)
          # unknown option
        ;;
  esac
    shift # past argument or value
done

echo ""
echo ""
mkdir -p ${octopus_agent_path}/lib/
lib_file_list=(wdd-lib-log.sh wdd-lib-sys.sh)
# shellcheck disable=SC2068
for lib_file in ${lib_file_list[@]}; do
    wget "${oss_url_prefix}/${lib_file}" -qO "${octopus_agent_path}/lib/${lib_file}"
    echo "加载库文件 < ${octopus_agent_path}/lib/${lib_file}"
    # shellcheck disable=SC1090
    . "${octopus_agent_path}/lib/${lib_file}"
done

# debug
#lib_file_list=(wdd-lib-sys.sh wdd-lib-log.sh )
#for lib_file in ${lib_file_list[@]} ; do
#    echo "加载库文件 < ${octopus_agent_path}/lib/${lib_file}"
#    . "${octopus_agent_path}/lib/${lib_file}"
#done



##  安装所需要的程序，及依赖程序
install_demand_softwares() {
  local software=""
  # shellcheck disable=SC2068
  for software in $@; do
    ## 安装该软件
    if [[ -n $(command -v "${software}") ]]; then
      colorEchoGreen "${software}已经安装了...跳过..."
      echo ""
    else
      log "正在安装 ${software}..."

      ## 判断该软件是否安装成功
      if ! $cmd_install "${software}"; then
        error "安装 ${software} 失败。"
        error "如果是重要软件，本脚本会自动终止！！"
        colorEchoPurple "一般软件，本脚本会忽略错误并继续运行，请之后手动安装该程序。"
        return 1
      else
        log "已经成功安装  ${software}"
        SplitGreen
      fi
    fi
  done
  return 0
}

#######################################
# description
# Globals:
#   BLUE
#   GREEN
#   linux_release_version
# Arguments:
#  None
#######################################
shutdown_firewall() {
  ## 关闭防火墙、SElinux、Swap
  FunctionStart "关闭系统的防火墙"

  systemctl stop firewalld
  systemctl disable firewalld
  SplitBlue

  if [ "${linux_release_version}" = "centos" ]; then
    colorEchoGreen "当前系统的发行版为-- ${linux_release_version}！！"
    SplitGreen
    log "开始关闭SELinux……"
    setenforce 0
    sed -i "s/SELINUX=enforcing/SELINUX=disabled/g" /etc/selinux/config
    colorEchoGreen "      SELinux关闭完成      "
  else
    colorEchoGreen "当前系统的发行版为-- ${linux_release_version}！！"
    systemctl stop ufw
    systemctl disable ufw
    colorEchoGreen "无需关闭SELinux，现在 跳过"
  fi

  FunctionEnd
}

#######################################
# description
# Globals:
#   oss_url_prefix
# Arguments:
#  None
#######################################
add_octopus_host() {
  FunctionStart "添加Octopus自定义Hosts！"

  cat >/etc/hosts <<EOF
127.0.0.1       localhost $(hostname)
# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost   ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts
127.0.1.1     $(hostname)

EOF

  log "开始下载 自定义的Hosts文件"
  wget "$oss_url_prefix/wdd-server-host.txt" -O /tmp/wdd-server-host.txt
  cat /tmp/wdd-server-host.txt >>/etc/hosts

  if grep -q "140.238" </etc/hosts; then
    colorEchoGreen "自定义hosts添加成功！"
    SplitGreen
  fi

  FunctionEnd
}

#######################################
# description
# Globals:
#   BLUE
#   GREEN
# Arguments:
#  None
#######################################
disable_swap() {
  FunctionStart "关闭系统的虚拟内存"
  swapoff -a
  colorEchoGreen "      虚拟内存关闭完成      "
  SplitGreen
  log "正在备份系统的文件系统表……"
  cp -f /etc/fstab /etc/fstab_bak
  colorEchoGreen "      备份完成      "
  echo ""
  log "正在修改文件系统表，去除虚拟内存的部分……"
  grep -v swap  </etc/fstab_bak   >/etc/fstab
  colorEchoGreen "      修改完成      "
  FunctionEnd
}

## 安装docker时，修改系统的配置文件
modify_system_config_docker() {
  FunctionStart "修改系统内核参数"
  ## 配置内核参数
  cat >/etc/sysctl.d/k8s.conf <<EOF
net.ipv4.ip_forward = 1
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
EOF

  ## 执行命令以应用
  sysctl -p /etc/sysctl.d/k8s.conf
  colorEchoGreen "--------------系统内核参数修改的结果如上所示----------------"
  SplitGreen
  log "系统参数修改成功，开始重启docker的服务！！"
  systemctl daemon-reload
  systemctl restart docker
  FunctionEnd
}

#######################################
# description
# Globals:
#   BLUE
#   cmd_remove
#   deploy_in_cn
#   docker_version
#   GREEN
#   linux_release_version
#   RED
#   pre_one
# Arguments:
#  None
# Returns:
#   $? ...
#######################################
install_docker() {
  ### 依赖colorEcho
  FunctionStart "安装Docker => 版本为 ${docker_version}"
  SplitBlue

  ## 清理docker环境
  log "开始清理docker环境，卸载先前的相关安装内容！！"
  systemctl stop docker
  systemctl disable docker
  local pre_soft_ware=(docker-ce containerd.io docker-ce-cli docker-compose kubelet kubeadm kubectl)
  local pre_one=""
  # shellcheck disable=SC2068
  for pre_one in ${pre_soft_ware[@]}; do
     $cmd_remove "$pre_one"
  done

  colorEchoGreen "----------docker环境清理完成----------"
  SplitGreen

  colorEchoGreen "当前系统的发行版为-- ${linux_release_version}！！"
  SplitLine

  if [[ $linux_release_version == "centos" ]]; then
    ## 安装docker的依赖
    log "正在安装安装docker的依赖"
    install_demand_softwares yum-utils device-mapper-persistent-data lvm2
    colorEchoGreen "----------docker的依赖安装完成----------"
    SplitGreen

    log "清理docker的源信息"
    rm -rf /etc/yum.repos.d/docker-ce.repo
    SplitBlue

    if [[ $deploy_in_cn -eq 1 ]]; then
      ## 添加docker的yum源
      log "正在添加中科院的docker的yum源…………"
      yum-config-manager --add-repo https://mirrors.ustc.edu.cn/docker-ce/linux/centos/docker-ce.repo
    else
      yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
    fi
    echo ""

    if [[ -f /etc/yum.repos.d/docker-ce.repo ]]; then
      if [[ $deploy_in_cn -eq 1 ]]; then
        log "替换docker的下载地址为ustc的镜像！"
        sed -i 's/download.docker.com/mirrors.ustc.edu.cn\/docker-ce/g' /etc/yum.repos.d/docker-ce.repo
      fi
      echo ""
      log "可以安装的docker-ce的 ${docker_version} 版本为："
      colorEchoGreen "--------------------------------------------------------------"
      yum list docker-ce --showduplicates | grep -w "${docker_version}" | awk '{print$2}' | cut -d ":" -f2 | sort -n -t - -k 1.7
      colorEchoGreen "--------------------------------------------------------------"
      echo ""

      colorEchoGreen "开始安装docker-ce，版本为${docker_version}"
      install_demand_softwares docker-ce-"${docker_version}" docker-ce-cli-"${docker_version}" containerd.io || return $?
    else
      error "docker的yum源添加失败，请手动添加"
    fi

  else
    log "开始安装相关的Docker基础组件"
    install_demand_softwares apt-transport-https ca-certificates curl gnupg software-properties-common lsb-release
    colorEchoGreen "      基础组件安装成功      "
    echo ""

    log "清理docker的源信息"
    rm -rf /etc/apt/sources.list.d/docker.list
    SplitBlue

    if [[ $deploy_in_cn -eq 1 ]]; then
        log "开始添加中科大的docker源的apt-key"
        curl -fsSL https://mirrors.ustc.edu.cn/docker-ce/linux/ubuntu/gpg | sudo apt-key add -
        colorEchoGreen "      添加成功      "
        echo ""
        log "开始添加中科大的docker源的apt源"
        add-apt-repository \
          "deb [arch=$(dpkg --print-architecture)] https://mirrors.ustc.edu.cn/docker-ce/linux/ubuntu $(lsb_release -cs) stable"
        colorEchoGreen "      添加成功      "
        echo ""
    else
        log "开始添加Docker官方的docker源的apt-key"
        install -m 0755 -d /etc/apt/keyrings
        curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
        chmod a+r /etc/apt/keyrings/docker.gpg
        colorEchoGreen "      apt-key 添加成功      "
        echo ""
        log "开始添加 Docker官方 的docker源的apt源"
        echo \
          "deb [arch="$(dpkg --print-architecture)" signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \
          "$(. /etc/os-release && echo "$VERSION_CODENAME")" stable" \
                                                                     | sudo tee /etc/apt/sources.list.d/docker.list >/dev/null
        colorEchoGreen "     apt源添加成功      "
        echo ""
    fi

    log "正在执行更新操作！！"
    apt-get update
    colorEchoGreen "----------更新完成----------"
    SplitGreen
    log "可以安装的docker-ce的${docker_version}版本为："
    colorEchoGreen "--------------------------------------------------------------"
    apt-cache madison docker-ce | grep -w "${docker_version}" | awk '{print$3}'
    colorEchoGreen "--------------------------------------------------------------"
    echo ""

    colorEchoGreen "开始安装docker-ce，版本为${docker_version}"

    local real_docker_stag=$(apt-cache madison docker-ce-cli | grep -w "${docker_version}" | awk '{print$3}' | grep "${docker_version}")

    log "需要安装的docker版本为=> $real_docker_stag"

    install_demand_softwares "docker-ce-cli=${real_docker_stag}" "docker-ce=${real_docker_stag}" containerd.io || return $?
  fi
  echo ""

  colorEchoGreen "----------安装完成----------"
  SplitGreen
  log "正在启动docker的服务进程…………"
  systemctl enable docker.service
  systemctl start docker.service
  colorEchoGreen "----------启动完成----------"
  echo ""
  FunctionEnd
}

#######################################
# description
# Globals:
#   BLUE
#   GREEN
#   PURPLE
#   RED
# Arguments:
#  None
#######################################
install_docker_compose() {
  FunctionStart "开始安装 docker-compose "

  log "开始下载 +++++++++++++ docker-compose文件 ++++++++++++++"

  local docker_compose_oss_url="https://b2.107421.xyz/docker-compose-linux-x86_64-v2.18.0"

  curl -L "${docker_compose_oss_url}" \
    -o /usr/local/bin/docker-compose
  if [[ -e /usr/local/bin/docker-compose ]]; then
    log "docker-compose文件下载成功！！"
    echo ""
    chmod +x /usr/local/bin/docker-compose

    if docker-compose --version &>/dev/null; then
      colorEchoGreen "docker-compose安装成功！！版本为 $(docker-compose --version | cut -d" " -f4) 尽情享用"
    else
      ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose
    fi
  else
    error "docker-compose文件下载失败！！ 无法访问github的资源。。"
    error "请手动下载docker-compose的安装文件！"
  fi
  FunctionEnd
}

set_system_security(){
  
}

#######################################
# description
# Globals:
#   BLUE
#   deploy_in_cn
#   RED
#   i
# Arguments:
#  None
# Returns:
#   $? ...
#######################################
install_zsh() {
  FunctionStart "安装宇宙第一shell工具zsh"
  SplitLine

  install_demand_softwares zsh git || return $?
  # 脚本会自动更换默认的shell
  if [[ $deploy_in_cn -eq 1 ]]; then
      echo y | REMOTE=https://gitea.107421.xyz/zeaslity/ohmyzsh.git sh -c "$(curl -fsSL https://gitea.107421.xyz/zeaslity/ohmyzsh/raw/branch/master/tools/install.sh)"
  else
      echo y | sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
  fi
  SplitLine
  log
  if modify_zsh; then
    log "开始修改默认shell为zsh……"
    local i
    for i in {6..1..-1}; do
      log "倒计时开始 ->> $i 秒 <<-，准备切换shell，下文的日志输出将会消失！！"
      sleep 2
    done
    chsh -s /bin/zsh
    zsh
  else
    error "zsh 安装失败，大概率是已经安装！！小概率是无法连接GitHub服务器~~"
  fi
  FunctionEnd
}

#######################################
# description
# Globals:
#   BLUE
#   deploy_in_cn
#   GREEN
#   PURPLE
# Arguments:
#  None
#######################################
modify_zsh() {
  FunctionStart "修改zsh的相关配置信息"
  SplitLine

  cat >~/oh-my-zsh-plugins-list.txt <<EOF
https://gitea.107421.xyz/zeaslity/ohmyzsh/src/branch/master/plugins/command-not-found/command-not-found.plugin.zsh
https://gitea.107421.xyz/zeaslity/ohmyzsh/src/branch/master/plugins/autojump/autojump.plugin.zsh
https://gitea.107421.xyz/zeaslity/ohmyzsh/src/branch/master/plugins/themes/themes.plugin.zsh
EOF
  log "正在下载zsh的一些好用的插件："
  echo ""

  if [[ $deploy_in_cn -eq 1 ]]; then
      log "开始从 Gitee 下载 自动补全 插件…………"
      git clone  https://gitee.com/wangl-cc/zsh-autosuggestions.git ~/.oh-my-zsh/plugins/zsh-autosuggestions
  else
      log "开始从 GitHub 下载 自动补全 插件…………"
      git clone  https://github.com/zsh-users/zsh-autosuggestions ~/.oh-my-zsh/plugins/zsh-autosuggestions
  fi
  SplitGreen

  if [[ $deploy_in_cn -eq 1  ]]; then
      log "开始从 Gitee 下载 命令高亮 插件…………"
      git clone  https://gitee.com/xiaoqqya/zsh-syntax-highlighting.git ~/.oh-my-zsh/plugins/zsh-syntax-highlighting
  else
      log "开始从 GitHub 下载 命令高亮 插件…………"
      git clone  https://github.com/zsh-users/zsh-syntax-highlighting.git ~/.oh-my-zsh/plugins/zsh-syntax-highlighting
  fi
  SplitGreen

  log "开始从JSDeliver下载插件…………"
  wget --timeout=3 -c -i ~/oh-my-zsh-plugins-list.txt -P ~/.oh-my-zsh/plugins/
  SplitGreen

  colorEchoGreen "插件已经下载完毕，现在开始修改zsh的配置文件…………"
  echo ""
  log "开始修改zsh的主题为 agnoster ！！"
  sed -i "s/robbyrussell/agnoster/g" ~/.zshrc
  sed -i 's/^# DISABLE_AUTO_UPDATE="true"/DISABLE_AUTO_UPDATE="true"/g' ~/.zshrc
  sed -i 's/plugins=(git)/plugins=(git zsh-autosuggestions zsh-syntax-highlighting command-not-found z themes)/g' ~/.zshrc
  echo ""
  colorEchoGreen "请检查当前zsh的插件开启情况："
  colorEchoGreen "------------------------------------------"
  grep "plugins=" </root/.zshrc | grep -v "\#"
  grep "plugins=" </root/.zshrc | grep -v "\#"
  grep "plugins=" </root/.zshrc | grep -v "\#"
  colorEchoGreen "------------------------------------------"

  echo ""
  echo "----------------------------------------------------"
  echo "这里的错误输出无需在意"
  source /root/.zshrc
  echo "这里的错误输出无需在意"
  echo "----------------------------------------------------"
  echo ""
  colorEchoGreen "zsh 安装成功，已更换主题，禁止更新，尽情享用~~~"
  SplitGreen
  colorEchoPurple "宇宙第一shell的zsh已经安装成功了！！！"
  colorEchoGreen "宇宙第一shell的zsh已经安装成功了！！！"
  log "宇宙第一shell的zsh已经安装成功了！！！"
  SplitGreen
  FunctionEnd
}

# 更换CentOS7的默认源
change_cent_os7default_repo() {
  FunctionStart
  mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup
  curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
  curl -o /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
  # curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.cloud.tencent.com/repo/centos7_base.repo
  yum clean all && yum makecache && yum update

  FunctionEnd
}

# 修改docker的国内加速镜像
change_docker_register_mirror() {
  FunctionStart "配置docker的国内加速镜像"
  SplitLine

  if [[ -e /etc/docker/daemon.json ]]; then
    log "已经存在docker的daemeon文件。。"
    mv /etc/docker/daemon.json /etc/docker/daemon.backup.json
    colorEchoGreen "已经将daemeon文件备份"
  fi
  log "正在写入docker的daemon配置文件……"
  cat >>/etc/docker/daemon.json <<EOF
{
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "100m"
  },
  "default-ulimits": {
    "nofile": {
      "Name": "nofile",
      "Hard": 655360,
      "Soft": 655360
    },
    "nproc": {
      "Name": "nproc",
      "Hard": 655360,
      "Soft": 655360
    }
  },
  "live-restore": true,
  "max-concurrent-downloads": 10,
  "max-concurrent-uploads": 10,
  "storage-driver": "overlay2",
  "storage-opts": [
    "overlay2.override_kernel_check=true"
  ],
  "registry-mirrors": [
        "https://jxlws3de.mirror.aliyuncs.com",
        "https://docker.mirrors.ustc.edu.cn",
        "https://hub-mirror.c.163.com",
        "https://registry.docker-cn.com"
  ]
}
EOF
  echo ""
  colorEchoGreen "配置文件写入完成，开始重启docker的服务！！"
  systemctl restart docker.service
  colorEchoGreen "----------docker服务重启完成----------"
  SplitGreen
  log "下面输出Docker加速镜像源的相关信息："
  echo "--------------------------------------------------------------------------------------"
  docker info | grep "https://" | grep -v "Registry"
  echo "--------------------------------------------------------------------------------------"
  colorEchoGreen "请查看上文是否存在添加的国内的镜像！！！"
  echo ""
  FunctionEnd
}

# 使用chrony进行NTP时间同步
time_sync_to_ali_by_chrony() {
  FunctionStart "使用 chrony 工具进行时间同步"

  log "开始安装chrony工具……"
  install_demand_softwares chrony || return $?
  colorEchoGreen "----------安装完成----------"
  # 这里使用的是 默认的NTP源，又不是不能用，为啥要换啊。
  sed -i "s/server 0.centos.pool.ntp.org iburst/server ntp2.aliyun.com iburst/g" /etc/chrony.conf

  systemctl restart chronyd

  if systemctl status chronyd -l | grep "active (running)" -q; then
    chronyc -n sources -v
    chronyc tracking

    colorEchoGreen "时间同步配置完成，已与阿里云进行时间同步！！"
    colorEchoGreen "NTP同步时间完成。现在时间为："
    colorEchoGreen "--------------------------------------------------"
    colorEchoPurple "$(date -R)"
    colorEchoGreen "--------------------------------------------------"
  else
    error "时间同步服务器启动失败！！"
    error "时间同步服务器启动失败！！"
    error "时间同步服务器启动失败！！"
    return 1
  fi

  change_time_zone_and_ntp

  FunctionEnd
}

#######################################
# description 修改时区为东八区的时间，并且开启NTP时间同步
# Globals:
#   BLUE
#   GREEN
#   PURPLE
#   RED
# Arguments:
#  None
#######################################
change_time_zone_and_ntp() {
  FunctionStart "使用 timedatectl 工具进行时间同步"

  if [[ -n $(command -v timedatectl) ]]; then
    log "检测到工具存在，正在设置时间和时区为 上海(UTC+8)时间"
    timedatectl set-timezone Asia/Shanghai && timedatectl set-ntp true
    colorEchoGreen "同步时间完成。现在时间为："
    colorEchoGreen "--------------------------------------------------"
    colorEchoPurple "$(date -R)"
    colorEchoGreen "--------------------------------------------------"
    log "开始重启系统日志服务，使得系统日志的时间戳也立即生效"
    systemctl restart rsyslog
    colorEchoGreen "----------重启完成----------"
  else
    error "timedatectl 工具不存在，时间同步失败！！ 请手动更换时间！"
  fi

  FunctionEnd
}

#######################################
# description 修改SSH的登录端口为 ${modify_ssh_port}
# Globals:
#   modify_ssh_port 需要修改的ssh_port
# Arguments:
#  None
#######################################
modify_ssh_port() {
  FunctionStart "开始修改SSH的登录端口为 ${modify_ssh_port}"

  local ssh_config_file="/etc/ssh/sshd_config"

  if [[ -s /etc/ssh/sshd_config_wdd_back ]]; then
      log "sshd_config文件已经备份跳过！"
  else
      cp /etc/ssh/sshd_config /etc/ssh/sshd_config_wdd_back
  fi
  SplitGreen

  # 修改sshd的配置
  local sshd_change_to_yes=("PermitRootLogin" "PasswordAuthentication" "TCPKeepAlive" "AllowTcpForwarding" "AllowAgentForwarding" "TCPKeepAlive")
  local sshd_change_to_no=("ChallengeResponseAuthentication" "PermitEmptyPasswords" "StrictModes")

  local yes_item
  # shellcheck disable=SC2068
  for yes_item in ${sshd_change_to_yes[@]}; do
    if grep -x "$yes_item yes" $ssh_config_file; then
      # 已经存在了，什么都不做
      :
    elif grep -x "#$yes_item yes" $ssh_config_file; then
      # 被 # 注释，需要解开
      sed -i "s/#$yes_item yes/$yes_item yes/g" $ssh_config_file
    elif grep -x "$yes_item no" $ssh_config_file; then
      # 被修改为no，需要改为yes
      sed -i "s/$yes_item no/$yes_item yes/g" $ssh_config_file
    else
      # 没有，那就添加
      sed -i "$ a $yes_item yes" $ssh_config_file
    fi
  done

  local no_item
  # shellcheck disable=SC2068
  for no_item in ${sshd_change_to_no[@]}; do
    if grep -x "$no_item no" $ssh_config_file; then
        :
    elif grep -x "#$no_item no" $ssh_config_file; then
        sed -i "s/#$no_item no/$no_item no/g" $ssh_config_file
    elif grep -x "$no_item yes" $ssh_config_file; then
        sed -i "s/$no_item yes/$no_item no/g" $ssh_config_file
    else
        sed -i "$ a $no_item no" $ssh_config_file
    fi
  done
  SplitGreen

  # 修改访问端口
  if grep -xw "Port ${modify_ssh_port}" $ssh_config_file &>/dev/null; then
        log "当前的ssh登录端口已经为${SSHLoginPort}，无需修改！"
  else
      if sed -i "/^#Port 22/a Port ${modify_ssh_port}" $ssh_config_file; then
      log "ssh的登陆端口已被修改为${modify_ssh_port}，请修改防火墙以开放该端口！！"
    fi
  fi
  SplitGreen

  # 修改ssh的连接中断延时
  log "修改ssh的连接中断延时!"
  echo "ClientAliveInterval 30" >>$ssh_config_file
  echo "ClientAliveCountMax 60" >>$ssh_config_file
  SplitGreen

  # 修改ssh的banner信息
  log "修改ssh的banner信息 !"
  wget $oss_url_prefix/octopus_ssh_banner -qO /etc/ssh/octopus_banner
  sed -i "s/#Banner none/Banner \/etc\/ssh\/octopus_banner/g" $ssh_config_file
  echo ""
  log "banner 内容为 => $(cat /etc/ssh/octopus_banner)"
  SplitGreen

  # 重启SSHD服务
  log "开始重启SSHD服务！"
  if systemctl restart sshd.service; then
      log "sshd.service服务已经重启完成！"
      colorEchoGreen "sshd文件已经修改成功，可以进行root登录，请修改root密码~~"
  else
      error "sshd服务重启失败，请检查原因!!!"
      error "如果是CentOS，大概率是防火墙的问题。"
  fi
  SplitGreen

  FunctionEnd
}

#######################################
# description
# Arguments:
#  None
# Returns:
#   1 ...
#######################################
modify_ssh_login() {
  FunctionStart "开始配置SSH 登录密钥！"

  if [[ ! -f /root/.ssh/id_rsa ]]; then
      log "未检测到 ssh rsa 密钥信息，开始生成！"
      ssh-keygen -t rsa -P "" -f /root/.ssh/id_rsa
  fi

  if grep $(cut -d " " -f3 <~/.ssh/id_rsa.pub)  <~/.ssh/authorized_keys; then
      log "本机的ssh-key信息已经写入，跳过！"
  else
      cat ~/.ssh/id_rsa.pub >>~/.ssh/authorized_keys
      chmod 600 ~/.ssh/authorized_keys
  fi
  SplitLine

  log "下载公共id_rsa.pub文件！"
  wget "$oss_url_prefix/ssh_key_pub.txt" -qO /tmp/ssh_key_pub.txt
  if [[ ! -s /tmp/ssh_key_pub.txt ]]; then
      error "下载 ssh-key 失败！"
      return 1
  fi

  log "开始写入ssh-key信息！"
  cat /tmp/ssh_key_pub.txt >>~/.ssh/authorized_keys

  if grep -q "DESKTOP-K2F9GG3" <~/.ssh/authorized_keys; then
      log $(grep "DESKTOP-K2F9GG3" <~/.ssh/authorized_keys)
      colorEchoGreen "      公共SSH-Key已经写入成功！    "
      SplitGreen
  fi

  FunctionEnd
}

## 为了本脚本能够满足Ubuntu系统，做出设当的更改
common_tool_install() {
  FunctionStart "安装Linux常用工具"
 
  colorEchoGreen "当前系统的发行版为-- ${linux_release_version} ！！"
  colorEchoGreen "当前系统的发行版为-- ${linux_release_version} ！！"
  colorEchoGreen "当前系统的发行版为-- ${linux_release_version} ！！"
  echo ""
  if [[ ${linux_release_version} == "centos" ]]; then
    local centos_common_tool=(deltarpm net-tools iputils bind-utils lsof curl wget vim mtr htop)
    # shellcheck disable=SC2068
    install_demand_softwares ${centos_common_tool[@]}
  elif [[ ${linux_release_version} == "ubuntu" ]] || [[ ${linux_release_version} == "debian" ]]; then
    local ubuntu_common_tool=(iputils-ping net-tools dnsutils lsof curl wget mtr-tiny vim htop lrzsz)
    # shellcheck disable=SC2068
    install_demand_softwares ${ubuntu_common_tool[@]}
  fi
  FunctionEnd
}

#######################################
# description
# Globals:
#   octopus_agent_path
# Arguments:
#  None
# Returns:
#   0 ...
#######################################
remove_octopus_agent() {

  FunctionStart "清理Octopus Agent"

  local systemd_config_path=("/lib/systemd/system/" "/etc/systemd/system/")

  local systemd_config_file
  local agent_installed=0
  # shellcheck disable=SC2068
  for systemd_config_file in ${systemd_config_path[@]}; do
      if ls "${systemd_config_file}"* | grep -q octopus-agent.service; then
          agent_installed=1
      fi
  done

  if [[ $agent_installed -eq 0 ]]; then
      log "octopus agent 没有安装！ 卸载成功！"
      return 0
  fi

  # 关闭服务
  log "开始关闭OctopusAgent的服务！"
  systemctl stop octopus-agent.service
  sleep 2
  SplitLine
  systemctl disable octopus-agent.service
  SplitLine

  log "删除OctopusAgent的守护进程配置文件！"
  rm -rf /etc/systemd/system/octopus-agent.service
  sleep 1
  systemctl daemon-reload
  # 删除残留
  SplitLine
  log "删除OctopusAgent的文件残留！"
  rm -rf ${octopus_agent_path}
  rm -rf "${octopus_agent_path}/lib"
  FunctionEnd
}
#######################################
# description
# Globals:
#   octopus_agent_path
# Arguments:
#  None
#######################################
daemon_octopus_agent() {
  #  https://www.baeldung.com/linux/run-java-application-as-service
  FunctionStart "[守护]-开始设置Agent的守护进程"

  cat >/etc/systemd/system/octopus-agent.service <<EOF
[Unit]
Description=Octopus Agent Service
Documentation=https://octopus.107421.xyz/
After=syslog.target network.target

[Service]
SuccessExitStatus=143
SyslogIdentifier=octopus-agent
User=root
Type=simple
WorkingDirectory=$octopus_agent_path
ExecStart=$octopus_agent_path/octopus-agent -version=standard
ExecStop=/bin/kill -15 \$MAINPID

[Install]
WantedBy=multi-user.target
EOF

  colorEchoBlue "开始配置Agent日志输出文件！"
  # https://www.benzhu.xyz/linux12/
  cat >/etc/rsyslog.d/octopus-agent.conf <<EOF
if \$programname == 'octopus-agent' then /var/log/octopus-agent.log
& stop
EOF

  rsyslogd -N1 -f /etc/rsyslog.d/octopus-agent.conf
  systemctl restart rsyslog

  colorEchoGreen "Agent守护程序设置成功！"

  FunctionEnd
}

get_octopus_agent_latest_version(){
    # 2024年4月8日
    FunctionStart "查询 Octopus Agent 最新的版本！"
    octopus_latest_version=$(curl -s -timeout=5 "${agent_version_url}")

    if [ "$octopus_latest_version" == "123" ]; then
        echo "find_octopus_latest_version error ! "
        return 233
    else
       echo "find_octopus_latest_version is => $octopus_latest_version"
    fi

    colorEchoGreen "Octopus Agent 最新的版本为 => $octopus_latest_version"
}

#######################################
# description
# Globals:
#   agent_config_url
#   file_array
#   linux_release
#   octopus_agent_path
#   octopus_agent_url
#   oss_url_prefix
# Arguments:
#  None
#######################################
install_octopus_agent() {
    FunctionStart "安装 Octopus Agent"

    colorEchoBlue "开始检查最新的版本！"

     # add for offline version
     if [[ $is_offline -eq 1 ]]; then
        octopus_agent_url="http://${offline_host_ip}/octopus-agent"
        agent_config_url="http://${offline_host_ip}/agent-config"
        agent_version_url="http://${offline_host_ip}/agent-version"
        colorEchoBlue "[install_octopus_agent] - offline agent url are => $octopus_agent_url"

     fi

#    local octopus_latest_version=""
#    octopus_latest_version=$(curl "$octopus_agent_url/" | grep -v h1 | grep "a href=" | head -1 | awk '{print$2}' | cut -d">" -f2 | cut -d"<" -f1 | cut -d"_" -f4-)
#
#    if [[ $latest_version == "" ]]; then
#        echo ""
#        colorEchoRed "[install_octopus_agent] - get agent version error ! break !"
#        colorEchoRed "[install_octopus_agent] - get agent version error ! break !"
#        echo ""
#        return 233
#    fi
    get_octopus_agent_latest_version

    log "查询得到的Octopus Agent的最新版本为 => ${octopus_latest_version}"
    SplitBlue
    # Agent二进制文件的命名规则为 octopus-agent_linux_amd64_<version>
    # shellcheck disable=SC2154
    local agent_latest_version="octopus-agent_linux_${linux_release}_${octopus_latest_version}"
    colorEchoBlue "octopus agent latest version is => [ $agent_latest_version ]"

    log "开始下载最新版本的Octopus Agent !"
    wget "${octopus_agent_url}/${agent_latest_version}" -qO "${octopus_agent_path}/${agent_latest_version}"
    SplitGreen
    cp "${octopus_agent_path}/$agent_latest_version" "${octopus_agent_path}/octopus-agent"
    chmod +x "${octopus_agent_path}/octopus-agent"
    echo ""
    colorEchoBlue "---------------- ls the ${octopus_agent_path} ----------------------"
    ls ${octopus_agent_path} | grep octopus-agent
    echo ""

    log "开始下载 Octopus Agent Config !"
    rm -rf index.html

    local agentConfigFileList=""
    agentConfigFileList=$(curl "$agent_config_url/" | grep -v h1 | grep "a href=" | awk '{print$2}' | cut -d">" -f2 | cut -d"<" -f1 | cut -d"_" -f4- | tr "\n" " ")

    IFS=" " read -ra file_array <<<"$agentConfigFileList"

    local agent_config
    for agent_config in "${file_array[@]}"; do
        colorEchoBlue "agent config file is => $agent_config"
        wget -q "$agent_config_url/$agent_config" -qO "${octopus_agent_path}/$agent_config"
        echo ""
    done

    colorEchoBlue "---------------- ls the ${octopus_agent_path} ----------------------"
    ls ${octopus_agent_path} | grep ".yaml"
    echo ""

#    log "开始配置Agent启动的基础环境信息"
#    rm -rf "$octopus_agent_path/lib/wdd-lib-env.sh"
#    wget "${oss_url_prefix}/wdd-lib-env.sh" -qO "${octopus_agent_path}/lib/wdd-lib-env.sh"
#    SplitGreen
#    log "开始收集Agent主机的信息!"
#    echo ""
#    chmod +x "${octopus_agent_path}/lib/wdd-lib-env.sh"
#    bash "${octopus_agent_path}/lib/wdd-lib-env.sh"
    echo "写入备份octopus-server-info-conf文件！"
    local agent_server_info_file="$octopus_agent_path/octopus-agent-back.conf"

  touch "$agent_server_info_file"
  cat >"$agent_server_info_file" <<EOF
serverName: ""
serverIpPbV4: ""
serverIpInV4: ""
serverIpPbV6: ""
serverIpInV6: ""
location: ""
provider: ""
managePort: ""
cpuCore: ""
cpuBrand: ""
memoryTotal: "$"
diskTotal: "$"
diskUsage: "$"
archInfo: ""
osInfo: ""
osKernelInfo: ""
tcpControl: ""
virtualization: ""
ioSpeed: ""
machineId: ""
agentVersion: ""
EOF
    echo ""
    SplitGreen

    # ok
    daemon_octopus_agent
    echo ""

    # change for it
    sed -i "s/OFFLINE_HOST_IP/${offline_host_ip}/g" ${octopus_agent_path}/octopus-agent-standard.yaml
    colorEchoGreen "[install_octopus_agent] - agent-config is ok !"
    # see the config file


    log "开始启动 Octopus Agent!"

    systemctl daemon-reload
    sleep 1
    systemctl enable octopus-agent.service
    systemctl restart octopus-agent.service

    cat - 1>&2  <<EOF

    查看Octopus Agent的运行日志 👇

      tail -f -n 1500 /var/log/octopus-agent.log

      journalctl -u octopus-agent.service -n 200 -f

    ----------------------------
    查看 Octopus Agent的运行状态    systemctl status octopus-agent.service -l

EOF

    FunctionEnd
}

update_octopus_agent(){
  FunctionStart "更新 Octopus Agent"

  # find octopus agent by service path
  local systemd_config_path=("/lib/systemd/system/" "/etc/systemd/system/")
  local systemd_config_file
  local agent_installed=0
  # shellcheck disable=SC2068
  for systemd_config_file in ${systemd_config_path[@]}; do
      if ls "${systemd_config_file}"* | grep -q octopus-agent.service; then
          agent_installed=1
      fi
  done

  if [[ $agent_installed -eq 0 ]]; then
      log "octopus agent 没有安装！ 关闭成功！"
      cat - 1>&2  <<EOF

           Octopus Agent 没有安装！ 请执行 --agent-install 命令进行安装

EOF
      return 2
  else
     # 关闭服务
      log "开始关闭OctopusAgent的服务！"
      systemctl stop octopus-agent.service
      sleep 2
  fi

  colorEchoBlue "开始检查最新的版本！"

  # add for offline version
  if [[ $is_offline -eq 1 ]]; then
    octopus_agent_url="http://$offline_host_ip/octopus-agent"
    agent_config_url="http://$offline_host_ip/agent-config"
    agent_version_url="http://${offline_host_ip}/agent-version"
    colorEchoBlue "[install_octopus_agent] - offline agent url are => $octopus_agent_url"
  fi

  get_octopus_agent_latest_version

  SplitBlue
  # Agent二进制文件的命名规则为 octopus-agent_linux_amd64_<version>
  local agent_latest_version="octopus-agent_linux_${linux_release}_${octopus_latest_version}"
  colorEchoBlue "octopus agent latest version is => [ $agent_latest_version ]"

  log "开始下载最新版本的Octopus Agent !"
  wget "${octopus_agent_url}/${agent_latest_version}" -qO "${octopus_agent_path}/${agent_latest_version}"
  SplitGreen
  cp "${octopus_agent_path}/$agent_latest_version" "${octopus_agent_path}/octopus-agent"
  chmod +x "${octopus_agent_path}/octopus-agent"
  echo ""
  colorEchoBlue "---------------- ls the ${octopus_agent_path} ----------------------"
  ls ${octopus_agent_path} | grep octopus-agent
  echo ""
  echo ""

  log "开始下载 Octopus Agent Config !"
  rm -rf index.html

  local agentConfigFileList=""
  agentConfigFileList=$(curl "$agent_config_url/" | grep -v h1 | grep "a href=" | awk '{print$2}' | cut -d">" -f2 | cut -d"<" -f1 | cut -d"_" -f4- | tr "\n" " ")

  IFS=" " read -ra file_array <<<"$agentConfigFileList"

  local agent_config
  for agent_config in "${file_array[@]}"; do
      colorEchoBlue "agent config file is => $agent_config"
      wget -q "$agent_config_url/$agent_config" -qO "${octopus_agent_path}/$agent_config"
      echo ""
  done

  colorEchoBlue "---------------- ls the ${octopus_agent_path} ----------------------"
  ls ${octopus_agent_path} | grep ".yaml"
  echo ""

  log "开始重启启动 Octopus Agent!"
 # change for it
  sed -i "s/OFFLINE_HOST_IP/${offline_host_ip}/g" ${octopus_agent_path}/octopus-agent-standard.yaml
  colorEchoGreen "[update_octopus_agent] - agent-config is ok !"

  systemctl enable octopus-agent.service
  systemctl start octopus-agent.service

    cat - 1>&2  <<EOF

    查看Octopus Agent的运行日志 👇

      tail -f -n 1500 /var/log/octopus-agent.log

      journalctl -u octopus-agent.service -n 200 -f

    ----------------------------
    查看 Octopus Agent的运行状态    systemctl status octopus-agent.service -l

EOF

    FunctionEnd
}

build_offline_host_ip(){
  
  FunctionStart "offline installation ! start to build for host ip !"
  
  local host_ip=""
  colorEchoBlue "[build_offline_host_ip] - offline install of octopus agent,  oss url is => ${oss_url_prefix}"
  host_ip=$(echo "$oss_url_prefix" | grep -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b")
  echo ""
  colorEchoBlue "[build_offline_host_ip] - make sure agent offline package has been synchronized to => $host_ip !"
  colorEchoBlue "[build_offline_host_ip] - make sure agent offline package has been synchronized to => $host_ip !"
  echo ""

  if [ "$host_ip" == "" ]; then
      colorEchoRed "[build_offline_host_ip] - offline host ip extraction error ! break !"
      return 233
  fi

  offline_host_ip=${host_ip}

  FunctionEnd
}





#######################################
# description
# Globals:
#   is_common_tool_install
#   is_disable_swap
#   is_install_docker
#   is_install_docker_compose
#   is_install_host
#   is_install_zsh
#   is_shutdown_firewall
# Arguments:
#  None
# Returns:
#   $? ...
#######################################
main() {
  check_root
  check_sys

  if [[ $is_offline -eq "1"   ]]; then
      build_offline_host_ip
  fi

  if [[ $is_shutdown_firewall -eq "1"   ]]; then
      shutdown_firewall
  fi

  if [[ $is_disable_swap -eq 1 ]]; then
     # 关闭虚拟缓存，k8s安装的时候才需要
      disable_swap
  fi

  if [[ $is_modify_ssh_login -eq 1 ]]; then
      modify_ssh_login
  fi

  if [[ $is_modify_ssh_port -eq 1 ]]; then
      modify_ssh_port
  fi

  if [[ $is_install_host -eq 1 ]]; then
      # 添加自我服务器的所有hosts
      add_octopus_host
  fi

  if [[ $is_common_tool_install -eq 1 ]]; then
      # 安装一些常用的小工具
      common_tool_install
  fi

  if [[ $is_install_docker -eq 1 ]]; then
      install_docker
      if [[ $deploy_in_cn -eq 1 ]]; then
        change_docker_register_mirror
      fi
  fi

  if [[ $is_install_docker_compose -eq 1 ]]; then
      install_docker_compose
  fi

  if [[ $is_set_security -eq 1 ]]; then
      set_system_security
  fi

  if [[ $is_install_agent -eq 1 ]]; then
      # 安装agent
      install_octopus_agent
  fi

  if [[ $is_update_agent -eq 1 ]]; then
      # 安装agent
      update_octopus_agent
  fi

  if [[ $is_remove_agent -eq 1 ]]; then
      # 卸载agent
      remove_octopus_agent
  fi

  if [[ $is_install_zsh -eq 1 ]]; then
      # 安装宇宙第一shell的zsh
      install_zsh
  fi

  # 使用chrony进行NTP时间同步--包含下面的设置
  # time_sync_to_ali_by_chrony || return $?

  # 使用timedatactl修改时间与时区【推荐】
  #  change_time_zone_and_ntp || return $?
}

main
