#!/bin/bash


NewVerion=""

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

RED="31m"    ## 姨妈红
GREEN="32m"  ## 水鸭青
YELLOW="33m" ## 鸭屎黄
PURPLE="35m" ## 基佬紫
BLUE="36m"   ## 天依蓝
BlinkRed="31;5m" ##闪烁的红色
BackRed="41m" ## 背景红色

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

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

# 判断命令是否存在
command_exists() {
	command -v "$@" >/dev/null 2>&1
}

#######   获取系统版本及64位或32位信息
check_sys() {
   sys_bit=$(uname -m)
   case $sys_bit in
   i[36]86)
       os_bit="32"
       release="386"
       ;;
   x86_64)
       os_bit="64"
       release="amd64"
       ;;
   *armv6*)
       os_bit="arm"
       release="arm6"
       ;;
   *armv7*)
       os_bit="arm"
       release="arm7"
       ;;
   *aarch64* | *armv8*)
       os_bit="arm64"
       release="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}"
        colorEcho ${GREEN} "-----------------------------------------------------------"
        echo ""
      fi
    fi
  done
  return 0
}

getNewVersion(){
    VersionURL="https://api.github.com/repos/cloudreve/Cloudreve/releases/latest"

    NewVerion=$(curl -s "${VersionURL}" --connect-timeout 60 | grep -w 'tag_name' | cut -d '"' -f4)

     if [ $? -ne 0 ] || [ ${NewVerion} == "" ]
     then
        colorEcho ${RED} "从GitHub获取 Cloudreve 的最新版本失败！！ "
        colorEcho ${RED} "大概率是由于无法访问github.com, 请检查网络！！"
        return 3
    fi
}

installCloudreve(){
    CloudreveFileName="cloudreve_${NewVerion}_linux_${release}.tar.gz"
    wget --no-check-certificate -v -N -T 10 https://github.com/cloudreve/Cloudreve/releases/download/${NewVerion}/${CloudreveFileName}

    if [ -s ${CloudreveFileName} ] || [ "$?" -eq "0" ]
    then
        tar -zxvf ${CloudreveFileName}
        chmod +x ./cloudreve

        if [ -d /home/cloudreve ]
        then
            mv ./cloudreve /home/cloudreve/
        else
            mkdir -p /home/cloudreve
            mv ./cloudreve /home/cloudreve/
        fi
        
        if [ -s /home/cloudreve/cloudreve ]; then
            colorEcho ${GREEN} "cloudreve-${NewVerion} 已经安装完成！！！"
            colorEcho ${GREEN} "安装的目录为 /home/cloudreve/"
            echo ""
        fi
    else
      echo ""
      colorEcho ${BlinkRed} "cloudreve安装包下载失败！！!"
      colorEcho ${BlinkRed} "cloudreve安装包下载失败！！!"
      echo ""
      colorEcho ${RED} "请检查网络，并重新运行此脚本！！"
      return 3
    fi
}

installNginx(){
  colorEcho ${BLUE} "开始通过 apt 或者 yum 的方式安装 nginx ！！"
  installDemandSoftwares nginx

  systemctl enable nginx
  systemctl start nginx

  systemctl status nginx | grep -q "Active: active (running)"
  if [  "$?" -eq "0" ]; then
      colorEcho ${GREEN} "nginx 安装完成，并成功运行！！"
  else
    colorEcho ${BlinkRed} "Nginx 安装失败！！！"
    colorEcho ${Red} "请查看nginx安装失败的原因！！"
    systemctl status nginx
  fi

}

configNginx(){
    nginx_pre_fix="/etc/nginx/conf.d"

    ServerName=$1

    if [ ${ServerName} = "" ];then
      colorEcho ${BLUE} "您没有传递域名参数！！  Cloudreve将使用ip+port的形式向外暴露！"
    else
      colorEcho ${BLUE} "开始配置Nginx反向代理的相关参数！"
      cat >>${nginx_pre_fix}/{ServerName} <<EOF
server {
    listen 443 ssl;
    ssl_certificate    /etc/ssl/cloudreve.example.com.crt;
    ssl_certificate_key    /etc/ssl/cloudreve.example.com.key;
    ssl_session_timeout 1d;
    ssl_session_cache shared:MozSSL:10m;
    ssl_session_tickets off;

    ssl_protocols   TLSv1.2 TLSv1.3;
    ssl_ciphers    ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;

    server_name    cloudreve.example.com;

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://127.0.0.1:5212;

        # 如果您要使用本地存储策略，请将下一行注释符删除，并更改大小为理论最大文件尺寸
        client_max_body_size 20000m;
    }
}
EOF
    sed -i "s/cloudreve.example.com/${ServerName}/g" ${nginx_pre_fix}/{ServerName}
    fi

    colorEcho ${BLUE} "开始重启Nginx！！"
    nginx -t && nginx -s reload

    if [ "$?" -eq "0" ]; then
        echo ""
        colorEcho ${GREEN} "Nginx 重启完成！！"
    fi
}

cloudreveSystemD(){
    echo ""
    colorEcho ${BLUE} "开始配置cloudreve的守护进程服务！！"
    if [ -d /usr/lib/systemd/system/ ]
    then
        systemDPath="/usr/lib/systemd/system"
    else
        systemDPath="/lib/systemd/system"
    fi

    cat >>${systemDPath}/cloudreve.service <<EOF
[Unit]
Description=Cloudreve
Documentation=https://docs.cloudreve.org
After=network.target
Wants=network.target

[Service]
WorkingDirectory=/home/cloudreve
ExecStart=/home/cloudreve/cloudreve
Restart=on-abnormal
RestartSec=5s
KillMode=mixed

StandardOutput=null
StandardError=syslog

[Install]
WantedBy=multi-user.target
EOF

   systemctl start cloudreve.service

   systemctl status cloudreve.service | grep -q "Active: active (running)"

   if [ "$?" -eq "0" ]; then
      echo ""
      colorEcho ${GREEN} "cloudreve已经成功运行！！"
      colorEcho ${GREEN} "请访问 curl localhost:5212 查看！！！"
      systemctl enable cloudreve.service
   else
      colorEcho ${BlinkRed} "cloudreve守护进程配置失败！！，请查看原因！"
      systemctl status cloudreve.servic -l
   fi
}


main(){
  check_sys
  check_root

  getNewVersion || return $?

  installCloudreve || return $?

  installNginx

  configNginx "pan.s1.107421.xyz"

  cloudreveSystemD

}

main