#!/bin/bash

# 显示
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m'

# 定义函数来显示结果
show_result() {
    local message=$1
    local status=$2		    
    if [ ${status} -eq 0 ];then
        echo -e "[${GREEN}  ok  ${NC}]\t$message"
    else
	echo -e "[${RED} fail ${NC}]\t$message"
    fi
}

# 使用说明
func_usage(){
    if [ $# -ne 1 ]; then
        echo "错误:需要一个参数。"
        echo "Usage: ${dirname}$0 9000"
        exit 1
    fi

    if ! [[ $1 =~ ^[0-9]+$ ]]; then
        echo "错误：参数必须是数字。"
        echo "Usage: ${dirname}$0 9000"
        exit 1
    fi
}

# 安装frpc
func_install_frpc(){
    echo "==========frpc配置=========="
    local frpc_port=$1
    if [ ! -e /lib/systemd/system/frpccustom.service ];then 
        [ ! -e /etc/frp ] && mkdir -p /etc/frp
	[ ! -e /usr/bin/frpc ] && ln -s /xyapp/system/miner.plugin-frpc.ipk/bin/frpc /usr/bin/frpc
	cat >/etc/frp/frpczj.ini<<EOF
[common]
server_addr = frpcbd.onething.net
server_port = 7900

[ssh-${frpc_port}]
type        = tcp
local_ip    = 127.0.0.1
local_port  = 22
remote_port = ${frpc_port}
EOF
        cat >/lib/systemd/system/frpccustom.service<<EOF 
[Unit]
Description=Frp Client Service
After=network.target

[Service]
Type=simple
User=root
Restart=on-failure
RestartSec=5s
ExecStart=/usr/bin/frpc -c /etc/frp/frpczj.ini
ExecReload=/usr/bin/frpc reload -c /etc/frp/frpczj.ini

[Install]
WantedBy=multi-user.target
EOF

        systemctl daemon-reload
        systemctl start frpccustom.service 
	show_result "Frpc installation" $?
	systemctl enable frpccustom.service >/dev/null 2>&1 
    else
	show_result "Frpc is already installed." 0 
    fi					  
}

func_base_config(){
    # 字节网卡硬件配置文件
    if [ ! -e /etc/zjfx.config ];then
        cat >/usr/local/setup_file_zjfx.sh<<'EOF'
#!/bin/bash
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

sys_disk=$(lsblk -l | egrep -B 1 "/$|boot|swap" | egrep -v "lvm|luks|--" | awk '{print $1}' | sed -e '/sd/s/[0-9]//' -e '/nvme/s/p[0-9]//' -e '/vd/s/[0-9]//' | sort|uniq)
data_disk=$(lsblk | grep -E "^s|^n|^v" | grep -v sr0 | awk '{print"/dev/"$1}' | grep -v ${sys_disk} | sort | tr '\n' ',' | sed s/,$//)
echo "DISKLIST=${data_disk}" > /tmp/zjfx.config

practicnic=$(cat /tmp/multidialstatus.json | jq -r .multidial[].practicnic)
if [ -z "${practicnic}" ];then
    zjnic=$(route -n | grep '^0.0.0.0' | awk '{print$NF}')
    echo "NICS=${zjnic}" >> /tmp/zjfx.config
else
    zjnic=$(echo ${practicnic} | sed 's/ /,/g')
    echo "NICS=${zjnic}" >> /tmp/zjfx.config
fi

if [ ! -e /etc/zjfx.config ];then
    cp -raf /tmp/zjfx.config  /etc/zjfx.config
else
   diff -q /tmp/zjfx.config /etc/zjfx.config
   if [ $? -ne 0 ];then
      cp -raf /tmp/zjfx.config /etc/zjfx.config
   fi
fi
EOF
        if [ $(grep -c 'setup_file_zjfx' /var/spool/cron/crontabs/root) -eq 0 ];then
            chattr -i /var/spool/cron/crontabs/root
            echo '*/30 * * * * /bin/bash /usr/local/setup_file_zjfx.sh &>/dev/null' >> /var/spool/cron/crontabs/root
        fi
        bash /usr/local/setup_file_zjfx.sh
        show_result "Add new configuration zjfx file." $?
    else
        show_result "The zjfx config has been generated." 0
    fi
    #set default route as ipv4
    if [ $(grep -v "^#" /etc/gai.conf | grep -c "precedence ::ffff:0:0/96 100") -eq 0 ];then
        echo "precedence ::ffff:0:0/96 100"  >> /etc/gai.conf
    fi
    # 
    apt autoremove -y linux-headers-4.19.117.bsk.3-amd64
    
}

# 升级httpproxy插件 
func_update_httpproxy(){
    echo "==========httpproxy插件更新=========="
    local_ver=$(xycall info plugin-httpproxy | jq -r .local_version)
    if [ $(echo ${local_ver} | grep -c '1.1.16') -eq 0 ];then
        xycall installurl https://grayscale.peiluyou.com/grayscale/mcloud_xykj_ipk/packages/plugin-httpproxy_1.1.16_xykj.ipk
        sleep 5
        xycall info plugin-httpproxy | jq -r .local_version | grep -q '1.1.16'
        show_result "httpproxy update" $?
    else
        show_result "httpproxy is already updated." 0
    fi
}

# 获取基础数据
func_obtain_basic_data(){
    local SN=$(cat /etc/xyapp/.efuse_sn)
    local host_name=$(cat /etc/xyapp/hostname)
    
    local max_attempts=5
    for attempt in $(seq 1 $max_attempts);do
        response=$(curl -s myip.ipip.net)	
	if [ -n "$response" ];then
            WAN_IP_ISP=${response}
            break
	fi
        sleep 1
    done
    
    if [ -e /etc/xyapp/export_bandwidth.json ];then 
        local line_number=$(jq '.line_number' /etc/xyapp/export_bandwidth.json)
        local per_line_bandwidth=$(jq '.per_line_bandwidth' /etc/xyapp/export_bandwidth.json)
        local total_bandwidth=$(echo ${line_number}*${per_line_bandwidth} | bc)
    fi

    intra_provincial_code=$(cat /xyapp/system/plugin-mdata/dockerTasksRecord.json | python -m json.tool | grep a562945659d73e5584b8cf54a23a0470 -C 20 | grep intra_provincial | awk -F':' '{print$NF}' | sed s/'[",]'//g)
    if [ ${intra_provincial_code} -eq  1 ];then
        intra_provincial='是'
    elif [ ${intra_provincial_code} -eq  2 ];then
	intra_provincial='否'
    else
        intra_provincial='未知'
    fi
    
    practicnic=$(jq -r '.multidial[0].practicnic' /tmp/multidialstatus.json)
    if [ "${practicnic}" == "null" ];then
        nic=$(route -n | grep "^0.0.0.0" | awk '{print$NF}' | head -n 1)
        local_ip=$(ifconfig ${nic} | grep -w inet | awk  '{print$2}')
        wan_ip=$(curl --interface ${nic} http://v5.douyinvod.com/ -H 'Host:ng-probe-status.bytedance.com' -v 2>&1 >/dev/null | grep "x-request-ip:" | awk -F":" '{print$NF}' | sed s/[[:space:]]//g)
    else
        local_ip=$(ifconfig ${practicnic} | grep -w inet | awk  '{print$2}')
        wan_ip=$(curl --interface ${practicnic} http://v5.douyinvod.com/ -H 'Host:ng-probe-status.bytedance.com' -v 2>&1 >/dev/null | grep "x-request-ip:" | awk -F":" '{print$NF}' | sed s/[[:space:]]//g)
    fi
    [ "${local_ip}" == "${wan_ip}" ] && nat1_yes_or_no="否" || nat1_yes_or_no="是"
 
    login_domain=$(cat /etc/frp/frpczj.ini | awk -F'=' '/server_addr/{print$2}')
    login_port=$(cat /etc/frp/frpczj.ini | awk -F'=' '/remote_port/{print$2}')
 
    echo "==========基础信息=========="
    width_label=1
    width_value=2
    printf "%-${width_label}s %-${width_value}s\n" "SN:" "${SN}"
    printf "%-${width_label}s %-${width_value}s\n" "hostname:" "${host_name}"
    printf "%-${width_label}s %-${width_value}s\n" "内网IP:" "10.0.1.2"
    printf "%-${width_label}s %-${width_value}s\n" "IP&区域&运营商:" "${WAN_IP_ISP:-NULL}"
    printf "%-${width_label}s %-${width_value}s\n" "线路数量:" "${line_number:-用户未设置}"
    printf "%-${width_label}s %-${width_value}s\n" "单线带宽:" "${per_line_bandwidth:-用户未设置}"
    printf "%-${width_label}s %-${width_value}s\n" "总体带宽:" "${total_bandwidth:-NULL}"
    printf "%-${width_label}s %-${width_value}s\n" "是否只覆盖本省:" "${intra_provincial:-NULL}"
    printf "%-${width_label}s %-${width_value}s\n" "是否NAT1内网资源:" "${nat1_yes_or_no:-NULL}"
    printf "%-${width_label}s %-${width_value}s\n" "frpc登录域名:" "${login_domain:-NULL}"
    printf "%-${width_label}s %-${width_value}s\n" "frpc登录端口:" "${login_port:-NULL}"
    
    echo "==========业务状态=========="
    if [ $(grep -c 58080 /xyapp/system/miner.plugin-activation.ipk/tools/recruit_tools) -eq 0 ];then
        cp -rfa  /xyapp/system/miner.plugin-activation.ipk/tools/recruit_tools{,.bak}
        sed -i 's/8080/58080/g' "/xyapp/system/miner.plugin-activation.ipk/tools/recruit_tools"
    fi
    /xyapp/system/miner.plugin-activation.ipk/tools/recruit_tools -p show
 
    echo "==========登录信息打印=========="
    echo "ssh root@frpcbd.onething.net -p ${login_port}"

    echo "==========登记信息打印=========="
    ISP=$(echo ${WAN_IP_ISP} | awk '{print$NF}' | sed s/[[:space:]]//g)
    area=$(echo ${WAN_IP_ISP} | sed "s/.*来自于：中国 //; s/ ${ISP}.*//" | sed s/[[:space:]]/-/)
    echo -e "深圳网心科技有限公司\t汇聚\t${ISP}\t${area}\t${SN}\t${intra_provincial}\t${total_bandwidth}\t${per_line_bandwidth}\t域名\t${login_domain}\t${login_port}\t${nat1_yes_or_no}"
}

# 修改ssh登录方式
func_ssh_config(){
    echo "==========SSH设置=========="
    if [ $(grep -c 'PasswordAuthentication no' /etc/ssh/sshd_config) -eq 0 ];then
        sed -i s/'PasswordAuthentication yes'/'PasswordAuthentication no'/g /etc/ssh/sshd_config
        sed -i /sshd/d /etc/hosts.allow
        sed -i /sshd/d /etc/hosts.deny
        systemctl restart sshd
        show_result "SSH Configuration" $?
    else
        show_result "SSH is already configured." 0
    fi
}


# 其他一些配置
func_other_settings(){
    
    # 不允许本地控制台公网登录
    [ -e /etc/xyapp/.allowIPPass ] && rm -rf /etc/xyapp/.allowIPPass
    cp -rf /xyapp/system/miner.plugin-activation.ipk/conf/activation.conf{,.bak1}
    sed -i s/0.0.0.0/127.0.0.1/g /xyapp/system/miner.plugin-activation.ipk/conf/activation.conf
    cd /xyapp/system/miner.plugin-activation.ipk
    ./stop.sh >/dev/null && ./start.sh > /dev/null
   
    # 修复本地web页面网卡状态显示
    mv /xyapp/system/miner.plugin-activation.ipk/bin/activation{,.bak}
    wget -q -O /xyapp/system/miner.plugin-activation.ipk/bin/activation http://tw15b0178.onething.net:9090/tool/superV/activation
    chmod 777 /xyapp/system/miner.plugin-activation.ipk/bin/activation
    cd /xyapp/system/miner.plugin-activation.ipk
    ./stop.sh >/dev/null && ./start.sh >/dev/null
    xycall blacklistadd  plugin-activation
}

# 主函数 
main(){

    func_usage "$@" 
    func_install_frpc "$@"
    func_base_config
    func_update_httpproxy
    func_other_settings
    func_obtain_basic_data
    func_ssh_config
    func_other_settings

}

# 脚本入口
main "$@"
