#!/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
    fi

    # 安装基础工具
    command -v jq &>/dev/null || yum -y install jq &>/dev/null
}
#
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
    systemctl enable sshd &> /dev/null
}
#
func_clean_lvm() {
    vg_group=`vgs | grep -v VG | awk -F ' ' '{print $1}' `
    while :
    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
        sleep 10
    done
    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
    #
    if lsblk | grep -q "^zram" ;then
        /xyapp/system/miner.plugin-perfoptimizer.ipk/script/zramstop
    fi
    dmsetup remove mpatha &> /dev/null
    dmsetup remove_all
}

#拉黑并停止插件
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-secore")
    for element in "${plugin_arr[@]}"; do
        func_determine_blacklisted ${element}
    done
}
#
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
    #appid=$(/xyapp/system/miner.plugin-activation.ipk/tools/recruit_tools -p show | grep appid | awk '{print$NF}')
    #[ -z "$appid" ] && (show_result "appid is empty" 1; exit 1)
    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 [ -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
        show_result "Frp has been installed." 0
    fi
    systemctl enable frpccustom.service &>/dev/null
    systemctl restart frpccustom.service
    show_result "Frp port ${frpc_port}" 0
}

func_setup_iptables(){
    # 配置防火墙 
    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 --dport 10000:10010 -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 --dport 10000:10010 -m comment --comment "TCP_MGTVPCDN" -j ACCEPT
fi 
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
}
#
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_clean_lvm
    func_inst_packages
    func_blacklistadd_plugin
    func_ssh_configuration
    func_setup_frpc
    func_setup_iptables
    func_setup_unziplog
}
# 脚本入口
main
if echo $0 | grep -q mginit.sh ;then
    exit 0
fi
while true;
do
    sleep 120
done
