#!/bin/bash
#!/bin/bash

OctopusAgentUrl=https://happybirthday.107421.xyz/octopus-agent/
OctopusAgentShell=https://happybirthday.107421.xyz/shell
AgentConfigUrl=https://happybirthday.107421.xyz/agent-config
OctopusAgentPath=/octopus-agent/shell
#####  environment variables ######

CMD_INSTALL=""
CMD_UPDATE=""
CMD_REMOVE=""
SOFTWARE_UPDATED=0
LinuxReleaseVersion=""
LinuxRelease=""

RED="31m"                          ## 姨妈红
GREEN="32m"                        ## 水鸭青
YELLOW="33m"                       ## 鸭屎黄
PURPLE="35m"                       ## 基佬紫
BLUE="36m"                         ## 天依蓝
BlinkGreen="32;5m"                 ##闪烁的绿色
BlinkRed="31;5m"                   ##闪烁的红色
BackRed="41m"                      ## 背景红色
SplitLine="----------------------" #会被sys函数中的方法重写

######## 颜色函数方法很精妙 ############
colorEcho() {
  echo -e "\033[${1}${*:2}\033[0m" 1>&2
}

#######################################
# description
# Globals:
#   EUID
#   RED
#   YELLOW
# Arguments:
#  None
#######################################
check_root() {
  if [[ $EUID != 0 ]]; then
    colorEcho ${RED} "当前非root账号(或没有root权限)，无法继续操作，请更换root账号!"
    colorEcho ${YELLOW} "使用sudo -命令获取临时root权限（执行后可能会提示输入root密码）"
    exit 1
  fi
}

#######################################
# description
# Globals:
#   PURPLE
#   SplitLine
# Arguments:
#  None
#######################################
FunctionStart() {
  colorEcho ${PURPLE} ${SplitLine}
  colorEcho ${PURPLE} ${SplitLine}
  echo ""
}

#######################################
# description
# Globals:
#   GREEN
#   SplitLine
# Arguments:
#  None
#######################################
FunctionSuccess() {
  colorEcho ${GREEN} ${SplitLine}
  echo ""
}

#######################################
# description
# Globals:
#   BlinkGreen
#   SplitLine
# Arguments:
#  None
#######################################
FunctionEnd() {
  echo ""
  colorEcho ${BlinkGreen} ${SplitLine}
  echo ""
  echo ""
}
# 判断命令是否存在
command_exists() {
  command -v "$@" >/dev/null 2>&1
}

#######   获取系统版本及64位或32位信息
check_sys() {
  # 获取当前终端的宽度，动态调整分割线的长度
  shellwidth=$(stty size | awk '{print $2}')
  SplitLine=$(yes "-" | sed ${shellwidth}'q' | tr -d '\n')

  sys_bit=$(uname -m)
  case $sys_bit in
    i[36]86)
      os_bit="32"
      LinuxRelease="386"
      ;;
    x86_64)
      os_bit="64"
      LinuxRelease="amd64"
      ;;
    *armv6*)
      os_bit="arm"
      LinuxRelease="arm6"
      ;;
    *armv7*)
      os_bit="arm"
      LinuxRelease="arm7"
      ;;
    *aarch64* | *armv8*)
      os_bit="arm64"
      LinuxRelease="arm64"
      ;;
    *)
      colorEcho ${RED} "
       哈哈……这个 辣鸡脚本 不支持你的系统。 (-_-) \n
       备注: 仅支持 Ubuntu 16+ / Debian 8+ / CentOS 7+ 系统
       " && exit 1
      ;;
  esac
  ## 判定Linux的发行版本
  if [ -f /etc/redhat-release ]; then
    LinuxReleaseVersion="centos"
  elif cat /etc/issue | grep -Eqi "debian"; then
    LinuxReleaseVersion="debian"
  elif cat /etc/issue | grep -Eqi "ubuntu"; then
    LinuxReleaseVersion="ubuntu"
  elif cat /etc/issue | grep -Eqi "centos|red hat|redhat"; then
    LinuxReleaseVersion="centos"
  elif cat /proc/version | grep -Eqi "debian"; then
    LinuxReleaseVersion="debian"
  elif cat /proc/version | grep -Eqi "ubuntu"; then
    LinuxReleaseVersion="ubuntu"
  elif cat /proc/version | grep -Eqi "centos|red hat|redhat"; then
    LinuxReleaseVersion="centos"
  else
    LinuxReleaseVersion=""
  fi

  # 判断系统的包管理工具  apt, yum, or zypper
  getPackageManageTool() {
    if [[ -n $(command -v apt-get) ]]; then
      CMD_INSTALL="apt-get -y -qq install"
      CMD_UPDATE="apt-get -qq update"
      CMD_REMOVE="apt-get -y remove"
    elif [[ -n $(command -v yum) ]]; then
      CMD_INSTALL="yum -y -q install"
      CMD_UPDATE="yum -q makecache"
      CMD_REMOVE="yum -y remove"
    elif [[ -n $(command -v zypper) ]]; then
      CMD_INSTALL="zypper -y install"
      CMD_UPDATE="zypper ref"
      CMD_REMOVE="zypper -y remove"
    else
      return 1
    fi
    return 0
  }

  # 检查系统包管理方式，更新包
  getPackageManageTool
  if [[ $? -eq 1 ]]; then
    colorEcho ${RED} "系统的包管理不是 APT or YUM, 请手动安装所需要的软件."
    return 1
  fi

  ### 更新程序引索
  if [[ $SOFTWARE_UPDATED -eq 0 ]]; then
    colorEcho ${BLUE} "正在更新软件包管理...可能花费较长时间…………"
    $CMD_UPDATE
    SOFTWARE_UPDATED=1
  fi
  return 0
}

##  安装所需要的程序，及依赖程序
installDemandSoftwares() {
  for software in "$@"; do
    ## 安装该软件
    if [[ -n $(command -v ${software}) ]]; then
      colorEcho ${GREEN} "${software}已经安装了...跳过..."
      echo ""
    else
      colorEcho ${BLUE} "正在安装 ${software}..."
      $CMD_INSTALL ${software}
      ## 判断该软件是否安装成功
      if [[ $? -ne 0 ]]; then
        colorEcho ${RED} "安装 ${software} 失败。"
        colorEcho ${RED} "如果是重要软件，本脚本会自动终止！！"
        colorEcho ${PURPLE} "一般软件，本脚本会忽略错误并继续运行，请之后手动安装该程序。"
        return 1
      else
        colorEcho ${GREEN} "已经成功安装  ${software}"
        FunctionSuccess
        echo ""
      fi
    fi
  done
  return 0
}

#######################################
# description
# Globals:
#   BLUE
#   DependLibFiles
#   OctopusAgentPath
#   RED
#   RepoSourcePath
#   libfile
# Arguments:
#  None
#######################################
DownloadAllFile() {

  FunctionStart

  colorEcho $RED "[CLEAN_UP] clean the old octopus agent staff !"
  rm -rf $OctopusAgentPath/lib
  rm -rf $OctopusAgentPath/

  mkdir -p $OctopusAgentPath
  mkdir -p $OctopusAgentPath/lib

  colorEcho $BLUE "start to download octopus agent !"

  CheckAndDownloadLatestVersion

  FunctionSuccess
  FunctionEnd

}

#######################################
# description
# Globals:
#   AgentConfigUrl
#   BLUE
#   GREEN
#   LinuxRelease
#   OctopusAgentUrl
#   agentConfig
#   agentConfigFileList
# Arguments:
#  None
#######################################
CheckAndDownloadLatestVersion() {
  FunctionStart

  colorEcho $BLUE "checking for the latest version"
  local latestVersion=$(curl $OctopusAgentUrl | grep -v h1 | grep "a href=" | head -1 | awk '{print$2}' | cut -d">" -f2 | cut -d"<" -f1 | cut -d"_" -f4-)

  rm -rf /octopus-agent/octopus-agent*
  cd /octopus-agent

  colorEcho $BLUE "start to download the latest version !"
  # Agent二进制文件的命名规则为 octopus-agent_linux_amd64_<version>
  local latestAgentVersion="octopus-agent_linux_${LinuxRelease}_${latestVersion}"
  colorEcho $BLUE ""
  colorEcho $BLUE "octopus agent latest version is => [ $latestAgentVersion ]"
  colorEcho $BLUE ""
  wget -q "$OctopusAgentUrl$latestAgentVersion"
  cp "$latestAgentVersion" octopus-agent
  chmod +x octopus-agent
  echo ""
  colorEcho $GREEN "---------------- ls the /octopus-agent ----------------------"
  ls /octopus-agent/ | grep octopus-agent
  echo ""

  colorEcho $BLUE "start to download the agent config!"
  rm -rf index.html
  agentConfigFileList=$(curl "$AgentConfigUrl/" | 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"

  for agentConfig in "${file_array[@]}"; do
      colorEcho $BLUE "agent config file is => $agentConfig"
      wget -q "$AgentConfigUrl/$agentConfig"
      echo ""
  done

  echo ""
  colorEcho $GREEN "---------------- ls the /octopus-agent ----------------------"
  ls /octopus-agent/ | grep ".yaml"
  echo ""

  FunctionSuccess
  FunctionEnd

}

#######################################
# description
# Globals:
#   JAVA_OPTS
# Arguments:
#  None
#######################################
systemdAgent() {

  #  https://www.baeldung.com/linux/run-java-application-as-service
  colorEcho $BLUE "[守护]-开始设置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
ExecStart=/octopus-agent/octopus-agent -agentServerInfoConf=/octopus-agent/octopus-agent.conf -version=shanghai
ExecStop=/bin/kill -15 \$MAINPID

[Install]
WantedBy=multi-user.target
EOF

  colorEcho ${BLUE} "开始配置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
}

## 为了本脚本能够满足Ubuntu系统，做出设当的更改
CommonToolInstall() {
  FunctionStart
  colorEcho ${BLUE} "开始进行Linux常用工具的安装过程…………"
  FunctionSuccess
  colorEcho ${GREEN} "当前系统的发行版为-- ${LinuxReleaseVersion} ！！"
  colorEcho ${GREEN} "当前系统的发行版为-- ${LinuxReleaseVersion} ！！"
  colorEcho ${GREEN} "当前系统的发行版为-- ${LinuxReleaseVersion} ！！"
  echo ""
  if [[ ${LinuxReleaseVersion} == "centos" ]]; then
    centosCommonTool=(deltarpm net-tools iputils bind-utils lsof curl wget vim mtr htop)
    installDemandSoftwares "${centosCommonTool[@]}"
  elif [[ ${LinuxReleaseVersion} == "ubuntu" ]] || [[ ${LinuxReleaseVersion} == "debian" ]]; then
    ubuntuCommonTool=(iputils-ping net-tools dnsutils lsof curl wget mtr-tiny vim htop lrzsz)
    installDemandSoftwares "${ubuntuCommonTool[@]}"
  fi
  FunctionEnd
}

#######################################
# description
# Globals:
#   BLUE
#   OctopusAgentPath
# Arguments:
#  None
#######################################
BootUPAgent() {

  FunctionStart

  colorEcho $BLUE "开始配置Agent启动的基础环境信息！"
  wget ${OctopusAgentShell}/octopus-env.sh -qO $OctopusAgentPath/lib/octopus-env.sh
  chmod +x $OctopusAgentPath/lib/octopus-env.sh
  echo ""
  colorEcho $BLUE "开始获取Agent的系统信息！"
  $OctopusAgentPath/lib/octopus-env.sh
  echo ""

  colorEcho $BLUE "start to daemon the octopus agent"
  systemdAgent

  colorEcho $BLUE "start the 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

  FunctionSuccess
  FunctionEnd
}

#######################################
# description
# Arguments:
#  None
#######################################
CleanOldOctopusAgent() {
    FunctionStart

    colorEcho $BLUE "start to kill old octopus-agent"

    agentPid=$(ps -ef | grep -v "color=" | grep -c "octopus-agent")
    if [[ $agentPid -gt 0 ]]; then
        colorEcho $BLUE "old agent existed ! start to kill"
        colorEcho $BLUE "old agent existed ! start to kill"
        systemctl stop octopus-agent
        sleep 2
        systemctl disable octopus-agent

        rm -rf /etc/systemd/system/octopus-agent.service
  fi

    FunctionSuccess
    FunctionEnd
}

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

  check_root
  check_sys

  CommonToolInstall

  # 不能使用下面的内容，会导致命令行执行的时候，本更新进程也会被杀死
  CleanOldOctopusAgent

  DownloadAllFile

  BootUPAgent

}

main
