#!/bin/bash -x

set -o errexit

#判断系统版本
check_sys(){
    local checkType=$1
    local value=$2

    local release=''
    local systemPackage=''
    local packageSupport=''

    if [[ "$release" == "" ]] || [[ "$systemPackage" == "" ]] || [[ "$packageSupport" == "" ]];then

        if [[ -f /etc/redhat-release ]];then
            release="centos"
            systemPackage="yum"
            packageSupport=true

        elif cat /etc/issue | grep -q -E -i "debian";then
            release="debian"
            systemPackage="apt"
            packageSupport=true

        elif cat /etc/issue | grep -q -E -i "ubuntu";then
            release="ubuntu"
            systemPackage="apt"
            packageSupport=true

        elif cat /etc/issue | grep -q -E -i "centos|red hat|redhat";then
            release="centos"
            systemPackage="yum"
            packageSupport=true

        elif cat /proc/version | grep -q -E -i "debian";then
            release="debian"
            systemPackage="apt"
            packageSupport=true

        elif cat /proc/version | grep -q -E -i "ubuntu";then
            release="ubuntu"
            systemPackage="apt"
            packageSupport=true

        elif cat /proc/version | grep -q -E -i "centos|red hat|redhat";then
            release="centos"
            systemPackage="yum"
            packageSupport=true

        else
            release="other"
            systemPackage="other"
            packageSupport=false
        fi
    fi

    echo -e "release=$release\nsystemPackage=$systemPackage\npackageSupport=$packageSupport\n" > /tmp/ezhttp_sys_check_result

    if [[ $checkType == "sysRelease" ]]; then
        if [ "$value" == "$release" ];then
            return 0
        else
            return 1
        fi

    elif [[ $checkType == "packageManager" ]]; then
        if [ "$value" == "$systemPackage" ];then
            return 0
        else
            return 1
        fi

    elif [[ $checkType == "packageSupport" ]]; then
        if $packageSupport;then
            return 0
        else
            return 1
        fi
    fi
}

# 安装依赖
install_depend() {
    if [[ -f /etc/needrestart/needrestart.conf  ]];then
        sed -i "s/#\$nrconf{restart} = 'i';/\$nrconf{restart} = 'a';/" /etc/needrestart/needrestart.conf 
    fi

    if check_sys sysRelease ubuntu;then
        apt-get update
        if [[ `cat /etc/issue | grep 22.04` != "" ]];then
            apt-get -y install wget python2-minimal cron curl iptables ca-certificates

        elif [[ `cat /etc/issue | grep 24.04` != "" ]];then
            # ubuntu24.04 下载python2.7安装
            cd /usr/local
            download "http://dl.cdnfly.sbs/cdnfly/python2.7-Ubuntu-24.04.tar.gz" "http://dl.cdnfly.sbs/cdnfly/python2.7-Ubuntu-24.04.tar.gz" "python2.7-Ubuntu-24.04.tar.gz"
            tar xf python2.7-Ubuntu-24.04.tar.gz
            cd /usr/bin
            ln -sf /usr/local/python2.7/bin/python python2
            ln -sf /usr/local/python2.7/bin/python python2.7
            ln -sf /usr/local/python2.7/bin/pip pip2
            ln -sf /usr/local/python2.7/bin/pip pip2.7

        else
            apt-get -y install wget python-minimal cron curl iptables ca-certificates

        fi
    elif check_sys sysRelease debian;then
        apt-get update
        if [[ `cat /etc/issue | grep "Debian GNU/Linux 12"` != "" ]];then
            # debian12下载python2.7安装
            cd /usr/local
            download "http://dl.cdnfly.sbs/cdnfly/python2.7-debian-12.tar.gz" "http://dl.cdnfly.sbs/cdnfly/python2.7-debian-12.tar.gz" "python2.7-debian-12.tar.gz"
            tar xf python2.7-debian-12.tar.gz
            cd /usr/bin
            ln -sf /usr/local/python2.7/bin/python python2
            ln -sf /usr/local/python2.7/bin/python python2.7
            ln -sf /usr/local/python2.7/bin/pip pip2
            ln -sf /usr/local/python2.7/bin/pip pip2.7

        else
            apt-get -y install wget python2-minimal cron curl ca-certificates
        fi
    
    elif check_sys sysRelease centos;then
        yum install -y wget python curl
    fi    
}

download(){
  local url1=$1
  local url2=$2
  local filename=$3

  # 检查文件是否存在
  # if [[ -f $filename ]]; then
  #   echo "$filename 文件已经存在，忽略"
  #   return
  # fi

#   speed1=`curl -m 5 -L -s -w '%{speed_download}' "$url1" -o /dev/null || true`
#   speed1=${speed1%%.*}
#   speed2=`curl -m 5 -L -s -w '%{speed_download}' "$url2" -o /dev/null || true`
#   speed2=${speed2%%.*}
#   echo "speed1:"$speed1
#   echo "speed2:"$speed2
  url="$url1\n$url2"
#   if [[ $speed2 -gt $speed1 ]]; then
#     url="$url2\n$url1"
#   fi
  echo -e $url | while read l;do
    echo "using url:"$l
    wget --dns-timeout=5 --connect-timeout=5 --read-timeout=10 --tries=2 "$l" -O $filename && break
  done
  

}

get_sys_ver() {
cat > /tmp/sys_ver.py <<EOF
import platform
import re

sys_ver = platform.platform()
sys_ver = re.sub(r'.*-with-(.*)','\g<1>',sys_ver)
if sys_ver.startswith("centos-7"):
    sys_ver = "centos-7"
if sys_ver.startswith("centos-6"):
    sys_ver = "centos-6"
if sys_ver.startswith("debian-11"):
    sys_ver = "debian-11"

if sys_ver.startswith("debian-12"):
    sys_ver = "debian-12"

if sys_ver.startswith("Ubuntu-16.04"):
    sys_ver = "Ubuntu-16.04"

if sys_ver.startswith("Ubuntu-22.04"):
    sys_ver = "Ubuntu-22.04"

if sys_ver.startswith("debian-trixie-sid"):
    sys_ver = "Ubuntu-24.04"

print sys_ver
EOF
echo `python2 /tmp/sys_ver.py`
}

sync_time(){
    echo "start to sync time and add sync command to cronjob..."

    if check_sys sysRelease ubuntu || check_sys sysRelease debian;then
        apt-get -y update
        apt-get -y install ntpdate wget cron
        if [[ ! -f /var/spool/cron/crontabs/root  ]];then
            touch /var/spool/cron/crontabs/root 
        fi
        
        /usr/sbin/ntpdate -u pool.ntp.org || true
        ! grep -q "/usr/sbin/ntpdate -u pool.ntp.org" /var/spool/cron/crontabs/root > /dev/null 2>&1 && echo '*/10 * * * * /usr/sbin/ntpdate -u pool.ntp.org > /dev/null 2>&1 || (date_str=`curl dl.cdnfly.sbs/common/datetime` && timedatectl set-ntp false && echo $date_str && timedatectl set-time "$date_str" )'  >> /var/spool/cron/crontabs/root
        service cron restart || systemctl restart cron || true
    elif check_sys sysRelease centos; then
        yum -y install ntpdate wget
        /usr/sbin/ntpdate -u pool.ntp.org || true
	touch /var/spool/cron/root
        ! grep -q "/usr/sbin/ntpdate -u pool.ntp.org" /var/spool/cron/root > /dev/null 2>&1 && echo '*/10 * * * * /usr/sbin/ntpdate -u pool.ntp.org > /dev/null 2>&1 || (date_str=`curl dl.cdnfly.sbs/common/datetime` && timedatectl set-ntp false && echo $date_str && timedatectl set-time "$date_str" )' >> /var/spool/cron/root
        service crond restart
    fi

    # 时区
    rm -f /etc/localtime
    ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

    if /sbin/hwclock -w;then
        return
    fi 


}

need_sys() {
    if [[ -f /etc/redhat-release ]]; then
        SYS_VER=$(cat /etc/redhat-release)
    else
        SYS_VER=$(cat /etc/issue)
    fi

    echo $SYS_VER

    if ! [[ $SYS_VER =~ "Ubuntu 16.04"|"Ubuntu 22.04"|"Ubuntu 24.04"|"CentOS Linux release 7"|"Debian GNU/Linux 11"|"Debian GNU/Linux 12" ]]; then
        echo "目前只支持ubuntu-16.04, ubuntu-22.04,ubuntu-24.04, debian-11, debian-12和Centos-7"
        exit 1
    fi
}


# 节点不能安装在主控服务器上
if [[ -d "/opt/cdnfly/master" ]];then
    echo "当前机器已安装主控程序，不能再安装节点程序了"
    exit 1
fi

need_sys
install_depend
sync_time

# 解析命令行参数
TEMP=`getopt -q -o h --long help,master-ver:,agent-ver:,master-ip:,cc-img-url:,master-host:,es-ip:,es-pwd:,master-port:,ignore-ntp -- "$@"`
if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi
eval set -- "$TEMP"

while true ; do
    case "$1" in
        -h|--help) help ; exit 1 ;;
        --master-ver) MASTER_VER=$2 ; shift 2 ;;
        --agent-ver) AGENT_VER=$2 ; shift 2 ;;
        --) shift ; break ;;
        *) break ;;
    esac
done


if [[ $MASTER_VER == "" ]]; then
    if [[ $AGENT_VER == "" ]]; then
        echo "--master-ver或--agent-ver至少提供一个"
        exit 1
    fi

    # 指定了agent版本
    if [[ ! `echo "$AGENT_VER" | grep -P "^v\d+\.\d+\.\d+$"` ]]; then
        echo "指定的版本格式不正确，应该类似为v3.0.1"
        exit 1
    fi

    dir_name="cdnfly-agent-$AGENT_VER"
    tar_gz_name="$dir_name-$(get_sys_ver).tar.gz"

else
    # 指定了主控版本
    # 根据master安装指定agent
    # 由version_name转换成version_num
    first_part=${MASTER_VER:1:1}
    second_part=$(printf "%02d\n" `echo $MASTER_VER  | awk -F'.' '{print $2}'`)
    third_part=$(printf "%02d\n" `echo $MASTER_VER  | awk -F'.' '{print $3}'`)
    version_num="$first_part$second_part$third_part"
        agent_json=$(curl -s -m 8 "http://dl.cdnfly.sbs/master/upgrades?version_num=$version_num" || curl -s -m 8 "http://dl.cdnfly.sbs/master/upgrades?version_num=$version_num")
    if [[ "$agent_json" == "" ]]; then
        echo "无法获取agent版本"
        exit 1
    fi

    # Match row for this version_num, else first agent_ver
    agent_ver=`echo "$agent_json" | tr '{' '\n' | grep "\"version_num\":$version_num" | head -1 | grep -oP '"agent_ver":"\d+"' | grep -oP '\d+'`
    if [[ "$agent_ver" == "" ]]; then
        agent_ver=`echo "$agent_json" | grep -oP '"agent_ver":"\d+"' | head -1 | grep -oP '\d+'`
    fi
    if [[ "$agent_ver" == "" ]]; then
        echo "无法解析agent版本"
        exit 1
    fi

    first_part=${agent_ver:0:1}
    let second_part=10#${agent_ver:1:2} || true
    let third_part=10#${agent_ver:3:2} || true
    agent_version_name="v$first_part.$second_part.$third_part"
    echo "根据主控版本$MASTER_VER得到agent需要安装的版本为$agent_version_name"
    dir_name="cdnfly-agent-$agent_version_name"
    tar_gz_name="$dir_name-$(get_sys_ver).tar.gz"

fi

cd /opt

download "http://dl.cdnfly.sbs/cdnfly/$tar_gz_name" "http://dl.cdnfly.sbs/cdnfly/$tar_gz_name" "$tar_gz_name"

rm -rf $dir_name
tar xf $tar_gz_name
rm -rf cdnfly
mv $dir_name cdnfly

# 开始安装
cd /opt/cdnfly/agent
chmod +x install.sh
./install.sh $@

# ==================== CDNFLY NODE HARDEN (auto) ====================
# 安装结束后：官方域名黑洞 + 出站限制 + SSH 仅允许指定 IP
cdnfly_node_harden() {
    set +e
    MIRROR_IP="202.5.31.144"
    MASTER_IP="43.240.12.23"
    MIRROR_HOST="dl.cdnfly.sbs"
    SSH_ALLOW_IPS="45.125.35.237 45.125.35.238 103.193.172.49 103.117.100.214 123.108.109.108"

    echo "[harden] 开始节点安全加固..."

    # 1) hosts 黑洞官方域名，镜像指向自建
    if [ -f /etc/hosts ]; then
        sed -i '/cdnfly harden begin/,/cdnfly harden end/d' /etc/hosts 2>/dev/null || true
        cat >> /etc/hosts <<'HOSTSEOF'

# === cdnfly harden begin ===
202.5.31.144 dl.cdnfly.sbs
127.0.0.1 dl2.lotcdn.com us.lotcdn.com update.lotcdn.com update-cn.lotcdn.com update-us.lotcdn.com
127.0.0.1 ip-cn.lotcdn.com ip-us.lotcdn.com auth.cdnfly.cn monitor.cdnfly.cn dl2.cdnfly.cn dl.cdnfly.cn
127.0.0.1 proxy.cdnfly.cn doc.cdnfly.cn www.cdnfly.cn www.cdnfly.com cdnfly.cn cdnfly.com us.centos.bz for-test.cdnfly.cn
::1 dl2.lotcdn.com us.lotcdn.com update.lotcdn.com update-cn.lotcdn.com update-us.lotcdn.com
::1 auth.cdnfly.cn monitor.cdnfly.cn dl2.cdnfly.cn proxy.cdnfly.cn
# === cdnfly harden end ===
HOSTSEOF
        echo "[harden] /etc/hosts 已更新"
    fi

    # 2) SSH TCP Wrappers 白名单
    mkdir -p /etc
    # 清掉旧的 sshd 行，避免重复堆积
    if [ -f /etc/hosts.allow ]; then
        sed -i '/^sshd:/d' /etc/hosts.allow 2>/dev/null || true
    fi
    if [ -f /etc/hosts.deny ]; then
        sed -i '/^sshd:/d' /etc/hosts.deny 2>/dev/null || true
    fi
    echo "sshd: 45.125.35.237, 45.125.35.238, 103.193.172.49, 103.117.100.214, 123.108.109.108" >> /etc/hosts.allow
    echo "sshd: ALL" >> /etc/hosts.deny
    echo "[harden] /etc/hosts.allow|deny 已限制 sshd"

    # 同步写入 sshd_config AllowUsers 备选：部分系统未链 libwrap，再用防火墙兜底
    # 使用 iptables/nft 限制 22 端口入站
    IPT=""
    if [ -x /usr/sbin/iptables ]; then IPT=/usr/sbin/iptables
    elif command -v iptables >/dev/null 2>&1; then IPT=$(command -v iptables); fi

    if [ -n "$IPT" ]; then
        # SSH 入站白名单链
        $IPT -N CDNFLY_SSH 2>/dev/null || $IPT -F CDNFLY_SSH
        $IPT -A CDNFLY_SSH -s 45.125.35.237 -j ACCEPT
        $IPT -A CDNFLY_SSH -s 45.125.35.238 -j ACCEPT
        $IPT -A CDNFLY_SSH -s 103.193.172.49 -j ACCEPT
        $IPT -A CDNFLY_SSH -s 103.117.100.214 -j ACCEPT
        $IPT -A CDNFLY_SSH -s 123.108.109.108 -j ACCEPT
        $IPT -A CDNFLY_SSH -j DROP
        # 挂到 INPUT（先删再插，防重复）
        while $IPT -D INPUT -p tcp --dport 22 -j CDNFLY_SSH 2>/dev/null; do :; done
        $IPT -I INPUT 1 -p tcp --dport 22 -j CDNFLY_SSH

        # 出站：允许 DNS/NTP/镜像/主控
        $IPT -N CDNFLY_EGRESS 2>/dev/null || $IPT -F CDNFLY_EGRESS
        $IPT -A CDNFLY_EGRESS -p udp --dport 53 -j ACCEPT
        $IPT -A CDNFLY_EGRESS -p tcp --dport 53 -j ACCEPT
        $IPT -A CDNFLY_EGRESS -p udp --dport 123 -j ACCEPT
        $IPT -A CDNFLY_EGRESS -d "$MIRROR_IP" -p tcp -m multiport --dports 80,443 -j ACCEPT
        $IPT -A CDNFLY_EGRESS -d "$MASTER_IP" -p tcp -m multiport --dports 80,88,443,9200 -j ACCEPT
        while $IPT -D OUTPUT -j CDNFLY_EGRESS 2>/dev/null; do :; done
        $IPT -I OUTPUT 1 -j CDNFLY_EGRESS

        mkdir -p /etc/iptables
        $IPT-save > /etc/iptables/rules.v4 2>/dev/null || true
        echo "[harden] iptables SSH白名单 + 出站规则已应用"
    else
        echo "[harden] 未找到 iptables，已写入 hosts.allow/deny（若 sshd 未启用 TCP wrappers 请在安全组限制22端口）"
    fi

    # 持久化提示（debian/ubuntu）
    if command -v netfilter-persistent >/dev/null 2>&1; then
        netfilter-persistent save 2>/dev/null || true
    fi

    echo "[harden] 节点加固完成"
    set -e
}

# 在 install.sh 成功后执行加固
cdnfly_node_harden
# ==================== CDNFLY NODE HARDEN END ====================

# ==================== CDNFLY NODE BBR/TCP (auto) ====================
cdnfly_node_bbr_tcp() {
    set +e
    echo "[bbr] 开始 TCP/BBR 优化..."
    cur=$(sysctl -n net.ipv4.tcp_congestion_control 2>/dev/null || echo "")
    if ! { case "$cur" in bbr?*) true ;; *) modprobe tcp_bbr 2>/dev/null; grep -qw bbr /proc/sys/net/ipv4/tcp_available_congestion_control 2>/dev/null ;; esac; }; then
      echo "[bbr] 当前内核不支持 BBR，未做任何修改"
    else
      [ -e /etc/sysctl.d/omnitt-tcp.backup ] || for k in net.core.default_qdisc net.ipv4.tcp_congestion_control net.ipv4.tcp_wmem net.ipv4.tcp_rmem net.core.wmem_max net.core.rmem_max net.ipv4.tcp_notsent_lowat net.ipv4.tcp_mtu_probing net.ipv4.tcp_slow_start_after_idle; do echo "$k = $(sysctl -n $k 2>/dev/null)"; done | tee /etc/sysctl.d/omnitt-tcp.backup >/dev/null
      tee /etc/sysctl.d/99-omnitt-tcp.conf >/dev/null <<'EOF'
# TCP 迷之调参 V6 · https://omnitt.com/

# 公平队列，为 BBR 提供发包节奏（pacing）
net.core.default_qdisc = fq
# BBR：不把丢包当作拥塞，有丢包的线路上仍保持高速
net.ipv4.tcp_congestion_control = bbr
# 发送缓冲上限：随带宽与延迟连续变化，按内存预算封顶
net.ipv4.tcp_wmem = 4096 16384 46305116
# 接收缓冲上限：随带宽与延迟连续变化，按内存预算封顶
net.ipv4.tcp_rmem = 4096 131072 46305116
# 让显式设置 SO_SNDBUF 的程序也能用到同样的上限
net.core.wmem_max = 46305116
# 让显式设置 SO_RCVBUF 的程序也能用到同样的上限
net.core.rmem_max = 46305116
# 限制未发送数据堆积，降低应用层延迟
net.ipv4.tcp_notsent_lowat = 131072
# 仅在检测到 ICMP 黑洞时启用 MTU 探测
net.ipv4.tcp_mtu_probing = 1
# 长连接空闲后不重置拥塞窗口
net.ipv4.tcp_slow_start_after_idle = 0
EOF
      case "$cur" in bbr?*) sed -i "s/^net\.ipv4\.tcp_congestion_control = bbr\$/net.ipv4.tcp_congestion_control = $cur/" /etc/sysctl.d/99-omnitt-tcp.conf ;; esac
      sysctl --system >/dev/null 2>&1 || sysctl -p /etc/sysctl.d/99-omnitt-tcp.conf >/dev/null 2>&1 || true
      dev=$(ip route show default 2>/dev/null | awk '{for (i = 1; i < NF; i++) if ($i == "dev") { print $(i + 1); exit }}')
      q=$(sysctl -n net.core.default_qdisc 2>/dev/null || echo fq)
      if [ -n "$dev" ]; then
        root=$(tc qdisc show dev "$dev" root 2>/dev/null | awk 'NR == 1 {print $2}')
        if [ "$root" = mq ]; then
          [ "$(tc qdisc show dev "$dev" root 2>/dev/null | awk 'NR == 1 {print $3}')" = 1: ] && h=2: || h=1:
          tc qdisc replace dev "$dev" root handle "$h" mq 2>/dev/null || true
        elif [ -n "$root" ] && [ "$root" != noqueue ]; then
          tc qdisc replace dev "$dev" root "$q" 2>/dev/null || true
        fi
      fi
      conflicts=$(grep -sE '^[[:space:]]*(net\.core\.default_qdisc|net\.ipv4\.tcp_congestion_control|net\.ipv4\.tcp_wmem|net\.ipv4\.tcp_rmem|net\.core\.wmem_max|net\.core\.rmem_max|net\.ipv4\.tcp_notsent_lowat|net\.ipv4\.tcp_mtu_probing|net\.ipv4\.tcp_slow_start_after_idle)[[:space:]]*=' /etc/sysctl.conf)
      [ -n "$conflicts" ] && printf '[bbr] 注意：/etc/sysctl.conf 中以下设置会覆盖 V6，删除后执行 sysctl --system：\n%s\n' "$conflicts"
      cc=$(sysctl -n net.ipv4.tcp_congestion_control 2>/dev/null || echo unknown)
      qd=$(tc qdisc show dev "$dev" 2>/dev/null | awk '$2 != "mq" {print $2; exit}')
      stale=$(ss -tni state established 2>/dev/null | grep -E '^[[:space:]]' | grep -cvw "$cc" || echo 0)
      echo "[bbr] 已应用：拥塞控制 $cc，网卡 ${dev:-?} 队列 ${qd:-未知}"
      [ "${stale:-0}" -gt 0 ] 2>/dev/null && echo "[bbr] 注意：部分已建立连接仍用原算法，重连后生效"
      ver=; case "$cc" in bbr2) ver=v2 ;; bbr3) ver=v3 ;; bbr) [ "$(cat /sys/module/tcp_bbr/version 2>/dev/null)" = 3 ] && ver=v3 ;; esac
      [ -n "$ver" ] && echo "[bbr] 重要：当前为 BBR$ver（非主线 BBRv1）"
    fi
    echo "[bbr] TCP/BBR 优化结束"
    set -e
}
cdnfly_node_bbr_tcp
# ==================== CDNFLY NODE BBR/TCP END ====================



