#!/bin/bash
# 环境
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

# 显示
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$(date "+%F %H:%M:%S") $message" | tee -a /tmp/mgconfig.log
    else
        echo -e "[${RED} fail ${NC}]\t$(date "+%F %H:%M:%S") $message" | tee -a /tmp/mgconfig.log
    fi
}
#
func_inst_packages(){
    # 更新YUM源
    if [ $(cat /etc/yum.repos.d/CentOS-Base.repo | grep -c 'mirrors.aliyun.com') -eq 0 ];then
        mv /etc/yum.repos.d/CentOS-Base.repo{,bak}
        wget -q -O /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo
        wget -q -O /etc/yum.repos.d/epel.repo https://mirrors.aliyun.com/repo/epel-7.repo
        yum clean all
    fi
    # 安装基础工具
    command -v jq &>/dev/null || yum -y install jq &>/dev/null
}
#
func_set_hostsallow(){
    cat > /etc/hosts.allow<<EOD
# allow lo
sshd:127.0.0.1:allow

# allow lan
sshd:10.0.0.0/255.0.0.0:allow
sshd:172.16.0.0/255.240.0.0:allow
sshd:172.32.0.0/255.255.0.0:allow
sshd:192.168.0.0/255.255.0.0:allow

# allow office & vpn
sshd:61.187.53.128/255.255.255.128:allow
sshd:175.6.15.0/255.255.255.0:allow
sshd:123.59.21.0/255.255.255.0:allow
sshd:113.247.251.0/255.255.255.192:allow
sshd:58.20.34.192/255.255.255.192:allow
sshd:113.247.251.128/255.255.255.224:allow
sshd:113.247.251.160/255.255.255.224:allow
sshd:218.76.45.96/255.255.255.224:allow
sshd:110.53.162.224/255.255.255.224:allow
sshd:113.247.232.112/255.255.255.240:allow
sshd:119.39.39.128/255.255.255.192:allow
sshd:124.232.146.128/255.255.255.192:allow
sshd:119.39.39.136:allow
sshd:124.232.146.140:allow

# allow manager server
sshd:123.59.23.184:allow
sshd:203.187.176.82:allow
sshd:123.59.21.117:allow
sshd:124.250.52.47:allow
sshd:175.6.15.89:allow
sshd:175.6.15.207:allow

# allow yun manager server
sshd:123.57.80.40:allow
sshd:123.56.255.8:allow
sshd:47.93.215.93:allow
sshd:81.70.217.217:allow
sshd:81.70.217.71:allow
sshd:81.70.217.61:allow
sshd:152.136.67.117:allow

# cat.imgo.tv
sshd:47.93.254.187:allow
sshd:152.136.150.118:allow
sshd:10.50.100.42:allow
sshd:10.43.43.46:allow
sshd:10.43.1.233:allow
sshd:10.200.130.31:allow

# xunlei
sshd:106.8.131.29:allow
sshd:116.132.219.218:allow
sshd:111.63.205.58:allow
sshd:111.63.205.96:allow
sshd:106.8.131.208:allow
sshd:116.132.218.57:allow
sshd:123.182.51.51:allow
sshd:116.132.216.187:allow
sshd:111.63.205.32:allow

sshd:ALL:deny
EOD
}
#
func_ssh_configuration(){
    # 配置秘钥
    [ ! -d /root/.ssh ] && (mkdir -p /root/.ssh && chmod 700 /root/.ssh)
    [ ! -e /root/.ssh/authorized_keys ] && (touch /root/.ssh/authorized_keys && chmod 600 /root/.ssh/authorized_keys)
    if [ $(grep -c 'root@wxzyz001' /root/.ssh/authorized_keys) -eq 0 ];then
    cat>/root/.ssh/authorized_keys<<EOF
ssh-rsa [payload removed: 372 characters] root@wxzyz001
ssh-rsa [payload removed: 368 characters] yunpeng2
ssh-dss [payload removed: 580 characters] hailong2@mgtv.com
ssh-rsa [payload removed: 372 characters] yaoliang@mgtv.com
EOF
        show_result "SSH keys configure." $?
    else
        show_result "SSH keys has been configured." 0
    fi
    if [ $(grep -c xunlei /etc/passwd) -eq 0 ];then
        useradd xunlei &> /dev/null
        chown -R xunlei:xunlei /home/xunlei
    fi
    #
    if [ ! -d /home/xunlei/.ssh ];then
        mkdir -p /home/xunlei/.ssh
        chmod 700 /home/xunlei/.ssh
        chown -R xunlei:xunlei /home/xunlei
    fi
    if [ ! -f /home/xunlei/.ssh/authorized_keys ];then
        touch /home/xunlei/.ssh/authorized_keys
        chmod 600 /home/xunlei/.ssh/authorized_keys
        chown -R xunlei:xunlei /home/xunlei
    fi
    #
    if [ $(grep -c 'root@wxzyz001' /home/xunlei/.ssh/authorized_keys) -eq 0 ];then
        cat>/home/xunlei/.ssh/authorized_keys<<EOD
ssh-rsa [payload removed: 372 characters] root@wxzyz001
EOD
    fi
    # 
    if [ $(netstat -tunlp | grep -w "0 0.0.0.0:22"|wc -l) -eq 0 ];then
        if [ $(grep -c "^Port 22" /etc/ssh/sshd_config) -ne 0 ];then
            sed -i 's/#Port 22/Port 22/' /etc/ssh/sshd_config
        else
            echo "Port 22" >> /etc/ssh/sshd_config
        fi
        if [ $(netstat -tunlp | grep -w "127.0.0.1:22" |wc -l) -ge 0 ];then
            sed -i '/^ListenAddress/d' /etc/ssh/sshd_config
            sed -i '/Port 22/aListenAddress 0.0.0.0' /etc/ssh/sshd_config
        fi
        systemctl restart sshd &> /dev/null
    fi
    systemctl enable sshd &> /dev/null
    if [ $(egrep -c '106.8.131.208|116.132.218.57|111.63.205.96' /etc/hosts.allow) -lt 3 ];then
        func_set_hostsallow
    elif [ $(egrep -c '123.59.23.184|47.93.254.187|175.6.15.207' /etc/hosts.allow) -lt 3 ];then
        func_set_hostsallow
    fi
}
#
func_clean_lvm() {
    vg_group=`vgs | grep -v VG | awk -F ' ' '{print $1}' `
    count=0
    while [ $count -lt 50 ];do
        umount -l /dev/mapper/XRVD*  &> /dev/null
        umount -l /dev/mapper/XYBM*  &> /dev/null
        lvremove -yf /dev/mapper/XRVD* &>/dev/null
        lvremove -yf /dev/mapper/XYBM* &>/dev/null
        for i in $vg_group
        do
            vgremove -yf $i &> /dev/null
        done

        vgs=$(vgs | grep -E "XRVD|XYBM" | grep -v grep)
        if [ -z "${vgs}" ]; then
            break
        fi
        lsblk | grep lvmdisk |awk '{print "umount -l "$NF}'|bash &> /dev/null
        lvs |grep -v LV|awk '{print "lvremove -f /dev/"$2"/"$1}'|sh &> /dev/null
        vgs |grep -v VG |awk '{print "vgremove -f "$1}'|sh &> /dev/null
        pvs |grep -v PV|awk '{print "pvremove -f "$1}'| sh &> /dev/null
        sleep 5
        count=$((count + 1))
    done
    #
    if lsblk | grep -q "^zram" ;then
        /xyapp/system/miner.plugin-perfoptimizer.ipk/script/zramstop
    fi
    dmsetup remove mpatha &> /dev/null
    dmsetup remove_all
    if [ $(lvs|wc -l) -ne 0 ];then
        show_result "lvm clean failed." 1
    elif [ $(vgs|wc -l) -ne 0 ];then
        show_result "lvm clean failed." 1
    elif [ $(vgs|wc -l) -ne 0 ];then
        show_result "lvm clean failed." 1
    else
        show_result "lvm clean success." 0
    fi
}

#拉黑并停止插件
func_blacklistadd_plugin(){
    # 判断是否拉黑
    func_determine_blacklisted(){
        plugin_name=$1
        if [ $(xycall blacklistshow | grep -c ${plugin_name}) -eq 0 ];then
            if [ -e /xyapp/system/miner.${plugin_name}.ipk/stop.sh ];then
                cd /xyapp/system/miner.${plugin_name}.ipk/
                [ -e stop.sh ] && ./stop.sh &>/dev/null
                [ -e start.sh ] && mv start.sh{,.bak_xykj}
            fi
            xycall blacklistadd ${plugin_name}
            show_result "blacklistadd  ${plugin_name}." $?
        else
            show_result "The ${plugin_name} has been blacklisted." 0
        fi
    }
    plugin_arr=("plugin-systemrestart" "plugin-minionk8s" "plugin-secore" "plugin-dockerd" "plugin-syspress")
    for element in "${plugin_arr[@]}"; do
        func_determine_blacklisted ${element}
    done

    # 拉黑插件
    if [ $(xycall blacklistshow | grep -c plugin-deploy) -eq 0 ];then
        xycall blacklistadd plugin-deploy
        if [ -d /xyapp/system/miner.plugin-deploy.ipk ];then
            cd /xyapp/system/miner.plugin-deploy.ipk
            [ -e stop.sh ] && ./stop.sh &>/dev/null
            [ -e start.sh ] && mv start.sh{,.bak_xykj}
            sleep 30
        fi
        if [ $(netstat -tulnp| grep deploy | grep -wc ':8900') -eq 0 ];then
            show_result "blacklistadd  plugin-deploy." $?
        fi
    else
            show_result "The plugin-deploy has been blacklisted." 0
    fi
    #
    if [ $(netstat -tulnp| grep deploy | grep -wc ':8900') -eq 0 ];then
        show_result "blacklistadd  plugin-deploy." $?
    else
        show_result "plugin-deploy not stop" 1
    fi
    #
    # 禁止自更新,防止误操作
    if [ $(grep -c 'update.peiluyou.com' /xyapp/xyipk/ipk_opkg.conf) -ne 0 ];then
        \cp -raf /xyapp/xyipk/ipk_opkg.conf{,.bak_xykj}
        sed -i s/'update.peiluyou.com'/'127.0.0.1'/g /xyapp/xyipk/ipk_opkg.conf
        show_result "The ipk_opkg configuration file update." $?
    else
        show_result "The ipk_opkg configuration file has been updated." 0
    fi
}
#update plugin
func_update_plugin(){
    plugin_name=$1
    req_ver=$2
    package_name=$3
    #min_ver=$(echo -e "$(xycall info ${plugin_name} | jq -r .local_version) \n${req_ver}" | sort -V | head -n 1)
    cur_ver=$(xycall info ${plugin_name} | jq -r .local_version)
    if [[ $(printf "%s\n" "${req_ver}" "${cur_ver}" | sort -V | tail -n 1) == "${cur_ver}" ]];then
        show_result "The ${plugin_name} has been updated." 0
    else
        xycall installurl "http://tw15b0178.onething.net:9090/tool/superV/${package_name}"
        sleep 60
        cur_ver=$(xycall info ${plugin_name} | jq -r .local_version)
        if [[ $(printf "%s\n" "${req_ver}" "${cur_ver}" | sort -V | tail -n 1) == "${cur_ver}" ]];then
            show_result "${plugin_name} update." 0
            cd /xyapp/system/miner.${plugin_name}.ipk
            ./stop.sh &>/dev/null && ./start.sh &>/dev/null
        else
            show_result "${plugin_name} update." 1
        fi
    fi
}
#
#升级插件
func_upgrade_plugin(){
    ## 更新配置文件
    if [ -d /xyapp/system/miner.plugin-activation.ipk ];then
        # 激活插件plugin-activation
        ## 更新插件
        func_update_plugin "plugin-activation" '2.25.1' "plugin-activation_2.25.1_xykj.ipk"
        if [ $(grep -c 58080 /xyapp/system/miner.plugin-activation.ipk/conf/activation.conf) -eq 0 ];then
            \cp -raf /xyapp/system/miner.plugin-activation.ipk/conf/activation.conf{,.bak_xykj}
            wget -q -O /xyapp/system/miner.plugin-activation.ipk/conf/activation.conf http://tw15b0178.onething.net:9090/tool/superV/activation.conf
            cd /xyapp/system/miner.plugin-activation.ipk
            ./stop.sh &>/dev/null && ./start.sh &>/dev/null
            show_result "The plugin-activation configuration file update." $?
        else
            show_result "The plugin-activation configuration file has been updated." 0
        fi

        if [ -f /xyapp/system/miner.plugin-activation.ipk/tools/recruit_tools ] ;then
            if [ $(grep -c 58080 /xyapp/system/miner.plugin-activation.ipk/tools/recruit_tools) -eq 0 ];then
                \cp -raf  /xyapp/system/miner.plugin-activation.ipk/tools/recruit_tools{,.bak_xykj}
                sed -i 's/8080/58080/g' "/xyapp/system/miner.plugin-activation.ipk/tools/recruit_tools"
                show_result "The recruit_tools update." $?
            else
                show_result "The recruit_tools has been updated." 0
            fi
        fi
        xycall blacklistadd plugin-activation
    fi
    # 代理插件plugin-httpproxy
    func_update_plugin "plugin-httpproxy" '1.1.62' "plugin-httpproxy_1.1.62_${TAG}.ipk"

    # 压测插件plugin-syspress
    func_update_plugin "plugin-syspress" '0.6.6' "plugin-syspress_0.6.6_${TAG}.ipk"

    # frp插件plugin-frpc.ipk
    func_update_plugin "plugin-frpc" '1.3.2' "plugin-frpc_1.3.2_${TAG}.ipk"

    # 流量统计插件
    func_update_plugin "plugin-tupleprobe" '1.0.4' "plugin-tupleprobe_1.0.4_${TAG}.ipk"

    #更新agent
    func_update_plugin "plugin-agent" '100.3.121' "plugin-agent_100.3.121_${TAG}.ipk"
}

#frpc
func_setup_frpc(){
    command -v jq &>/dev/null || yum -y install jq &>/dev/null
    # 获取后端分配端口
    sn=$(cat /etc/xyapp/.efuse_sn)
    [ -z "$sn" ] && (show_result "sn is empty" 1; exit 1)
    if [ "$TAG" == xykj ];then
        business_id=0
        appid="44ff4cb7e5e5ffa4d33e8d5fe87fd9cd"
    else
        business_id=1044
        appid=""
    fi
    frpc_port=0
    json_data="{\"sn\": \"${sn}\", \"appid\":\"${appid}\",\"business_id\":${business_id}}"
    frpc_port=$(curl -sL -X POST -H "Content-Type: application/json" -d "$json_data" --location 'https://miner-ex-service-sgp.onething.net/v2/api/port/generate_port'| jq .data.port)
    [ -z "$frpc_port" ] && (show_result "frpc_port is empty" 1; exit 1)
    #frpc_port=$1
    #
    if [ "${frpc_port}" == null ]; then
        show_result "Frp port is null" 1
    elif [ "${frpc_port}" == 0 -o "${frpc_port}" == "" ];then
        show_result "Frp port is null" 1
    elif [ -n "${frpc_port}" ];then
        show_result "Frp port: ${frpc_port}" 0
        [ ! -e /etc/frp ] && mkdir -p /etc/frp
        cat >/etc/frp/frpcmg.ini<<EOG
[common]
server_addr = frpcustomer.xinqiucc.com
server_port = 30976
admin_addr = "127.0.0.1"
admin_port = 7401
admin_user = "admin"
admin_password = "admin"

[ssh-${frpc_port}]
type        = tcp
local_ip    = 127.0.0.1
local_port  = 22
remote_port = ${frpc_port}
EOG
    else
        show_result "Frp port is empty" 1
    fi

    if [ ! -e /lib/systemd/system/frpccustom.service ];then
        [ ! -e /usr/bin/frpc ] && ln -s /xyapp/system/miner.plugin-frpc.ipk/bin/frpc /usr/bin/frpc
        cat >/lib/systemd/system/frpccustom.service<<EOH
[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/frpcmg.ini
ExecReload=/usr/bin/frpc reload -c /etc/frp/frpcmg.ini

[Install]
WantedBy=multi-user.target
EOH
        systemctl daemon-reload
        systemctl start frpccustom.service
        show_result "Frp install" $?
        systemctl enable frpccustom.service &>/dev/null
    else
        systemctl enable frpccustom.service &>/dev/null
        systemctl restart frpccustom.service
        show_result "Frp has restart" $?
    fi
}

func_setup_iptables(){
    # 配置防火墙 
    [ -f /var/spool/cron/root ] || touch /var/spool/cron/root
    if [ ! -e /usr/local/setup_iptables.sh ];then
        cat >/usr/local/setup_iptables.sh<<'EOK'
#!/bin/bash
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
#
if [ $(iptables -nvL  | grep -c UDP_MGTVPCDN) -eq 0 ];then
    iptables -I INPUT -p udp -m multiport --dports 9395,9396,10000:10100 -m comment --comment "UDP_MGTVPCDN" -j ACCEPT
fi
if [ $(iptables -nvL  | grep -c TCP_MGTVPCDN) -eq 0 ];then
    iptables -I INPUT -p tcp -m multiport --dports 9395,9396,10000:10100 -m comment --comment "TCP_MGTVPCDN" -j ACCEPT
fi 
# permit ssh
iplist=(
10.0.0.0/8
172.16.0.0/12
172.32.0.0/16
192.168.0.0/16
61.187.53.128/25
175.6.15.0/24
123.59.21.0/24
113.247.251.0/26
58.20.34.192/26
113.247.251.128/27
113.247.251.160/27
218.76.45.96/27
110.53.162.224/27
113.247.232.112/28
119.39.39.128/26
124.232.146.128/26
119.39.39.136
124.232.146.140
123.59.23.184
203.187.176.82
123.59.21.117
124.250.52.47
175.6.15.89
175.6.15.207
123.57.80.40
123.56.255.8
47.93.215.93
81.70.217.217
81.70.217.71
81.70.217.61
152.136.67.117
47.93.254.187
152.136.150.118
10.50.100.42
10.43.43.46
10.43.1.233
10.200.130.31
106.8.131.29
116.132.219.218
111.63.205.58
111.63.205.96
106.8.131.208
116.132.218.57
123.182.51.51
116.132.216.187
111.63.205.32
)
for ip in "${iplist[@]}" ;do
    if [ $(iptables -vnL | grep "RH-Firewall-1-INPUT" | wc -l ) -gt 0 ];then
        if [ $(iptables -vnL RH-Firewall-1-INPUT | grep "$ip" | wc -l ) -eq 0 ];then
            iptables -I RH-Firewall-1-INPUT -s $ip -p tcp -m tcp --dport 22 -j ACCEPT
        fi
        if [ $(iptables -vnL INPUT | grep RH-Firewall-1-INPUT | wc -l) -eq 0 ];then
            iptables -I INPUT -j RH-Firewall-1-INPUT
        fi
    else
        iptables -N RH-Firewall-1-INPUT
        iptables -I INPUT -j RH-Firewall-1-INPUT
        iptables -I RH-Firewall-1-INPUT -s $ip -p tcp -m tcp --dport 22 -j ACCEPT
    fi
done
EOK
        chmod +x /usr/local/setup_iptables.sh
        if [ $(grep -c 'setup_iptables' /var/spool/cron/root) -eq 0 ];then
            echo '*/30 * * * * /bin/bash /usr/local/setup_iptables.sh &>/dev/null' >> /var/spool/cron/root
        fi
        bash /usr/local/setup_iptables.sh
        show_result "Iptables configuration." $?
    else
        show_result "Iptables has been configured." 0
    fi
}

func_setup_unziplog(){
    if [ ! -e /usr/local/unzip_mgtv_accesslog.sh ];then
        cat > /usr/local/unzip_mgtv_accesslog.sh<<'EOD'
#!/bin/bash
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
base_dir='/mgtv/logs'
unzip_dir='/mgtv/unziplogs'
mkdir -p ${unzip_dir}

# 解压最新的日志
latest_zip_file=$(ls -fl ${base_dir}/access.log.*.gz | tail -1 | awk -F' ' '{print $NF}')
if [ -n ${latest_zip_file} ];then
    file_basename=$(basename ${latest_zip_file} '.gz')
    target_file=${unzip_dir}/${file_basename}
    if [ ! -f ${target_file} ];then
        gunzip -d ${latest_zip_file} -c >${target_file}
        if [ $? -ne 0 ];then
            echo "unzip ${latest_zip_file} failed"
        fi
    fi
fi

# 清理过期的解压日志
unzip_file_list=$(ls -fl ${unzip_dir}/access.log.* | awk -F' ' '{print $NF}')
deadline=$(date -d "6 hour ago" "+%Y%m%d%H%M")
for file in ${unzip_file_list}
do
    tm=$(echo ${file} | awk -F'.' '{print $3}')
    if [ ${tm} -lt ${deadline} -a $(echo ${file} | grep -c 'access.log.') -eq 1 ];then
        rm -rf ${file}
    fi
done
EOD
        chmod +x /usr/local/unzip_mgtv_accesslog.sh
    fi
    if [ $(grep -c 'unzip_mgtv_accesslog' /var/spool/cron/root) -eq 0 ];then
         chattr -i /var/spool/cron/root
         echo "5 * * * * sh /usr/local/unzip_mgtv_accesslog.sh >/dev/null 2>&1 &"  >> /var/spool/cron/root 
    fi
}


func_management_services(){
    # 开启docker服务
    if [ -f /usr/lib/systemd/system/docker.service ];then
        if grep -q "ExecStartPre=/usr/local/by-watcher/watcher"  /usr/lib/systemd/system/docker.service ;then
            sed -i '/ExecStartPre=\/usr\/local\/by-watcher\/watcher/d' /usr/lib/systemd/system/docker.service
        systemctl daemon-reload
        fi
    fi
    if systemctl status docker &>/dev/null ;then
        show_result "The docker service is already running." 0
    else
        systemctl stop docker.service
        systemctl stop docker.socket
        systemctl start docker
        show_result "systemctl start docker" $?
    fi
    systemctl enable docker &> /dev/null
    # 关闭xyipk更新服务
    systemctl status upgrade &>/dev/null && ((systemctl disable upgrade &>/dev/null && systemctl stop upgrade) && show_result "systemctl stop upgrade" $?) || show_result "The xyipk upgrade service has been stopped." 0
    # 配置ssh
    if [ $(cat /etc/ssh/sshd_config|grep -vE "^#"|grep "ListenAddress 127.0.0.1"|wc -l) -ne 0 ];then
        sed -i 's/ListenAddress 127.0.0.1/#ListenAddress 127.0.0.1/' /etc/ssh/sshd_config
        systemctl restart sshd
    fi
    if [ $(cat /etc/ssh/sshd_config | grep -c "#Port 22") -ne 0 ];then
        sed -i 's/#Port 22/Port 22/' /etc/ssh/sshd_config
        systemctl restart sshd
    elif [ $(cat /etc/ssh/sshd_config | grep -c "Port 22") -eq 0 ];then
        echo "Port 22" >>  /etc/ssh/sshd_config
        systemctl restart sshd
    fi
}
#
main(){
    #
    if [ -f /etc/xyapp/.sysname ];then
        TAG=$(cat /etc/xyapp/.sysname)
    else
        show_result "file /etc/xyapp/.sysname not exist" 1
        TAG=xybk
    fi
    #
    if [ "${TAG}" == "xr" ];then
        TAG=xykj
    fi
    #
    func_inst_packages
    func_blacklistadd_plugin
    func_upgrade_plugin
    func_ssh_configuration
    func_setup_frpc
    func_setup_iptables
    func_setup_unziplog
    func_management_services
    func_clean_lvm
}
# 脚本入口
main
if echo $0 | grep -q mginit.sh ;then
    exit 0
fi
while true;
do
    sleep 120
done
