#!/bin/bash

set -o errexit
export PIP_DISABLE_PIP_VERSION_CHECK=1

download(){
  # wget安装
  if [[ ! `which wget` ]]; then
    if check_sys sysRelease ubuntu;then
        apt-get install -y wget
    elif check_sys sysRelease centos;then
        yum install -y wget
    fi 
  fi

  local url1=$1
  local url2=$2
  local filename=$3
  
  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
  if [[ $speed2 -gt $speed1 ]]; then
    url=$url2
  fi
  echo "using url:"$url
  wget "$url" -O $filename

}

#判断系统版本
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
}

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("Ubuntu-16.04"):
    sys_ver = "Ubuntu-16.04"

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

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


upgrade_db() {
eval `grep MYSQL_PASS /opt/cdnfly/master/conf/config.py`
eval `grep MYSQL_IP /opt/cdnfly/master/conf/config.py`
eval `grep MYSQL_PORT /opt/cdnfly/master/conf/config.py`
eval `grep MYSQL_DB /opt/cdnfly/master/conf/config.py`
eval `grep MYSQL_USER /opt/cdnfly/master/conf/config.py`

eval `grep LOG_IP /opt/cdnfly/master/conf/config.py`
eval `grep LOG_PWD /opt/cdnfly/master/conf/config.py`

mysql -h$MYSQL_IP -u$MYSQL_USER -p$MYSQL_PASS -P$MYSQL_PORT $MYSQL_DB -e "show processlist"  | awk '{print $1}' | grep -v Id | xargs kill || true


# black ip
curl -u elastic:$LOG_PWD  -X PUT "$LOG_IP:9200/black_ip/_settings" -H 'Content-Type: application/json' -d'
{
  "index": {
    "max_result_window": 1000000
  }
}
'

# 修改elasticsearch
curl -u elastic:$LOG_PWD -X PUT "$LOG_IP:9200/_ingest/pipeline/nginx_access_pipeline?pretty" -H 'Content-Type: application/json' -d'
{
  "description" : "nginx access pipeline",
  "processors" : [
      {
        "dissect": {
          "field": "message",
          "ignore_failure": true,
          "pattern" : "%{nid}\t%{uid}\t%{upid}\t%{site_id}\t%{time}\t%{addr}\t%{method}\t%{scheme}\t%{host}\t%{host2}\t%{server_port}\t%{req_uri}\t%{protocol}\t%{status}\t%{bytes_sent}\t%{referer}\t%{user_agent}\t%{content_type}\t%{up_resp_time}\t%{cache_status}\t%{up_recv}\t%{country}\t%{province}\t%{city}\t%{req_header}\t%{resp_header}\t%{req_body}\t%{sip}"
         }
      },
      {
          "remove": {
            "field": "message"
          }      
      }           
  ]
}
'

curl -u elastic:$LOG_PWD  -X PUT "$LOG_IP:9200/_template/http_access_template" -H 'Content-Type: application/json' -d'
{
  "mappings": {
    "properties": {
      "nid":    { "type": "keyword" },  
      "uid":    { "type": "keyword" },  
      "upid":    { "type": "keyword" },  
      "site_id":    { "type": "keyword" }, 
      "time":   { "type": "date"  ,"format":"dd/MMM/yyyy:HH:mm:ss Z"},
      "addr":  { "type": "keyword"  }, 
      "method":  { "type": "keyword" }, 
      "scheme":  { "type": "keyword"  }, 
      "host":  { "type": "keyword"  },
      "host2":  { "type": "text" , "index":false }, 
      "server_port":  { "type": "keyword"  }, 
      "req_uri":  { "type": "keyword" ,"fields": {"path": {"type": "text","analyzer": "path_analyzer"}} }, 
      "protocol":  { "type": "text" , "index":false }, 
      "status":  { "type": "keyword"  }, 
      "bytes_sent":  { "type": "integer"  }, 
      "referer":  { "type": "keyword"  }, 
      "user_agent":  { "type": "text" , "index":false }, 
      "content_type":  { "type": "text" , "index":false }, 
      "up_resp_time":  { "type": "float" , "index":false,"ignore_malformed": true }, 
      "cache_status":  { "type": "keyword"  }, 
      "up_recv":  { "type": "integer", "index":false,"ignore_malformed": true  },
      "country":  { "type": "keyword"  }, 
      "province":  { "type": "keyword" }, 
      "city":  { "type": "text" , "index":false },
      "req_header":  { "type": "text" , "index":false },
      "resp_header":  { "type": "text" , "index":false },
      "req_body":  { "type": "text" , "index":false },
      "sip":  { "type": "text" , "index":false }
    }
  },  
  "index_patterns": ["http_access-*"], 
  "settings": {
    "number_of_shards": 1,
    "number_of_replicas": 0,
    "index.lifecycle.name": "access_log_policy", 
    "index.lifecycle.rollover_alias": "http_access",
    "analysis": {
        "analyzer": {
            "path_analyzer": {
            "tokenizer": "path_hierarchy",
            "filter": ["lowercase"]
            }
        },
        "tokenizer": {
            "path_hierarchy": {
            "type": "path_hierarchy",
            "delimiter": "/",
            "replacement": "/",
            "skip": 0
            }
        }
    }
  }
}
'
curl -s  -u elastic:$LOG_PWD  -X GET http://$LOG_IP:9200/_cat/indices/http_access-* | awk '{print $3}' | while read index;do
    curl -u elastic:$LOG_PWD  -XPUT "http://$LOG_IP:9200/$index/_mapping?pretty" -H 'Content-Type: application/json' -d '
    {
        "properties":{
            "req_header":  { "type": "text" , "index":false },
            "resp_header":  { "type": "text" , "index":false },
            "req_body":  { "type": "text" , "index":false },
            "sip":  { "type": "text" , "index":false }
        }
    }
    '

    # 1. 关闭索引
    curl -u elastic:$LOG_PWD -X POST "$LOG_IP:9200/$index/_close"

    # 2. 更新分析设置

    curl -u elastic:$LOG_PWD -X PUT "$LOG_IP:9200/$index/_settings" -H 'Content-Type: application/json' -d'
    {
        "settings": {
            "analysis": {
                "analyzer": {
                    "path_analyzer": {
                    "tokenizer": "path_hierarchy",
                    "filter": ["lowercase"]
                    }
                },
                "tokenizer": {
                    "path_hierarchy": {
                    "type": "path_hierarchy",
                    "delimiter": "/",
                    "replacement": "/",
                    "skip": 0
                    }
                }
            }
        }
    }'

    # 3. 重新打开索引
    curl -u elastic:$LOG_PWD -X POST "$LOG_IP:9200/$index/_open"


done

# black_ip
curl -XPUT "http://$LOG_IP:9200/black_ip_new" \
  -u "elastic:$LOG_PWD" \
  -H "Content-Type: application/json" \
  -d '{
    "mappings": {
        "properties": {
        "site_id":    { "type": "keyword" },  
        "ip":    { "type": "keyword" },  
        "filter":    { "type": "keyword" }, 
        "uid":  { "type": "keyword"  }, 
        "exp":  { "type": "keyword"  }, 
        "create_at":  { "type": "keyword"  },
        "position":  { "type": "keyword"  }
        }
    }
  }'

curl -XPOST "http://$LOG_IP:9200/_reindex" \
  -u "elastic:$LOG_PWD" \
  -H "Content-Type: application/json" \
  -d '{
    "source": {
      "index": "black_ip"
    },
    "dest": {
      "index": "black_ip_new"
    }
  }'

curl -XDELETE "http://$LOG_IP:9200/black_ip" \
  -u "elastic:$LOG_PWD"

curl -XPOST "http://$LOG_IP:9200/_aliases" \
  -u "elastic:$LOG_PWD" \
  -H "Content-Type: application/json" \
  -d '{
    "actions": [
      {
        "add": {
          "index": "black_ip_new",
          "alias": "black_ip"
        }
      }
    ]
  }'

cd /tmp
download "https://dl2.lotcdn.com/cdnfly/pymodule-master-20250618.tar.gz" "https://us.lotcdn.com/cdnfly/pymodule-master-20250618.tar.gz" "pymodule-master-20250618.tar.gz"
tar xf pymodule-master-20250618.tar.gz
cd pymodule-master-20250618
/opt/venv/bin/pip install --no-deps configparser-4.0.2-py2.py3-none-any.whl
/opt/venv/bin/pip install --no-deps zipp-1.2.0-py2.py3-none-any.whl
/opt/venv/bin/pip install --no-deps importlib_metadata-1.6.1-py2.py3-none-any.whl
/opt/venv/bin/pip install --no-deps singledispatch-3.4.0.3-py2.py3-none-any.whl
/opt/venv/bin/pip install --no-deps contextlib2-0.6.0.post1-py2.py3-none-any.whl
/opt/venv/bin/pip install --no-deps scandir-1.10.0.tar.gz
/opt/venv/bin/pip install --no-deps pathlib2-2.3.5-py2.py3-none-any.whl
/opt/venv/bin/pip install --no-deps importlib_resources-2.0.1-py2.py3-none-any.whl
/opt/venv/bin/pip install --no-deps netaddr-0.10.1-py2.py3-none-any.whl

# 升级log4j
cd /tmp
download "https://dl2.lotcdn.com/cdnfly/log4j-2.24.3.tar.gz" "https://us.lotcdn.com/cdnfly/log4j-2.24.3.tar.gz" "log4j-2.24.3.tar.gz"
tar xf log4j-2.24.3.tar.gz
cd log4j-2.24.3
\cp log4j-core-2.24.3.jar /usr/share/elasticsearch/lib/log4j-core-2.24.3.jar
\cp log4j-api-2.24.3.jar /usr/share/elasticsearch/lib/log4j-api-2.24.3.jar
\cp log4j-slf4j-impl-2.24.3.jar /usr/share/elasticsearch/modules/x-pack-security/log4j-slf4j-impl-2.24.3.jar
\cp log4j-1.2-api-2.24.3.jar /usr/share/elasticsearch/modules/x-pack-core/log4j-1.2-api-2.24.3.jar

rm -f /usr/share/elasticsearch/lib/log4j-core-2.11.1.jar
rm -f /usr/share/elasticsearch/lib/log4j-api-2.11.1.jar
rm -f /usr/share/elasticsearch/modules/x-pack-security/log4j-slf4j-impl-2.11.1.jar
rm -f /usr/share/elasticsearch/modules/x-pack-core/log4j-1.2-api-2.11.1.jar

supervisorctl  -c /opt/cdnfly/master/conf/supervisord.conf stop cc_auto_switch expiring_cert node_ip_dns node_monitor site_res_count site_sync task


# 升级数据库
cat > /tmp/_db.py <<'EOF'
# -*- coding: utf-8 -*-

import sys
sys.path.append("/opt/cdnfly/master/")
from view.util import get_ip_location,is_empty
from model.db import Db
import pymysql
import json
import datetime
import random
import importlib
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkcore.auth.credentials import AccessKeyCredential
from aliyunsdkcore.auth.credentials import StsTokenCredential
from aliyunsdkdysmsapi.request.v20170525.SendSmsRequest import SendSmsRequest
from aliyunsdkdysmsapi.request.v20170525.QuerySmsTemplateRequest import QuerySmsTemplateRequest

reload(sys) 
sys.setdefaultencoding('utf8')


def get_templ_content(auth, templ_id):
    auth = json.loads(auth)
    sms_aliyun_access_key_id = auth['sms_aliyun_access_key_id']
    sms_aliyun_access_key_secret = auth['sms_aliyun_access_key_secret']
    sms_aliyun_sign_name = auth['sms_aliyun_sign_name']

    credentials = AccessKeyCredential(sms_aliyun_access_key_id, sms_aliyun_access_key_secret)
    client = AcsClient(region_id='cn-shanghai', credential=credentials)
    request = QuerySmsTemplateRequest()
    request.set_accept_format('json')
    request.set_TemplateCode(templ_id)

    try:
        response = json.loads(client.do_action_with_exception(request))
        if response['Code'] == "OK":
            return True, response['TemplateContent']
        
        return False, response['Message']
        
    except ServerException as err:
        return False, err.message

conn = Db()
try:

    # 线路排序
    # sort字段
    if not conn.fetchone("SELECT column_name FROM information_schema.columns WHERE table_name = 'line' AND column_name = 'sort' "):
        conn.execute("alter table line add sort int(11);")
        conn.execute("update line set sort=100;")
        conn.commit()

    # 企业认证
    if not conn.fetchone("SELECT column_name FROM information_schema.columns WHERE table_name = 'user' AND column_name = 'company_name' "):
        conn.execute("alter table user add `company_name` varchar(50) after cert_verified;")
        conn.commit()

    if not conn.fetchone("SELECT column_name FROM information_schema.columns WHERE table_name = 'user' AND column_name = 'company_credit_code' "):
        conn.execute("alter table user add `company_credit_code` varchar(50) after company_name;")
        conn.commit()

    if not conn.fetchone("SELECT column_name FROM information_schema.columns WHERE table_name = 'user' AND column_name = 'company_verified' "):
        conn.execute("alter table user add `company_verified` boolean default 0 after company_credit_code;")
        conn.commit()

    if not conn.fetchone("select * from config where name='company_auth' "):
        conn.execute("insert into config values ('company_auth','{}','system','0','global', now(),now(),1,null); ")
        conn.commit()

    # 内置资源防护
    openresty_config = json.loads(conn.fetchone("select value from config where name='openresty-config'  and scope_name='global' ")['value'])
    openresty_config["internal_qps"] = 50
    openresty_config["internal_res_block_time"] = 3600
    openresty_config["internal_rule"] = [{"period":"120","reqs":"20"},{"period":"","reqs":""},{"period":"","reqs":""}]
    openresty_config["acme_ip"] = []
    openresty_config["well_known_auto_protect_count"] = 600
    openresty_config["well_known_protect_expire"] = 0
    openresty_config["block_page_not_counted"] = 1
    openresty_config["block_page_num_limit"] = 10
    openresty_config["force_default_page_cc"] = "0"
    openresty_config["auto_default_page_cc_qps"] = 100
    if openresty_config["site_block_qps"] == "2000":
        openresty_config["site_block_qps"] = "200"

    conn.execute("update config set value=%s where name='openresty-config'  and scope_name='global' ",json.dumps(openresty_config))
    conn.commit()

    # well-known防护
    if not conn.fetchone("SHOW TABLES LIKE 'acme_ip_log'"):
        conn.execute("create table acme_ip_log (`id` bigint(20) NOT NULL AUTO_INCREMENT,`ip` varchar(40),`create_at` int(11),primary KEY `id` (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;")
        conn.commit()

    # 实名充值
    config = json.loads(conn.fetchone("select value from config where name='recharge' and type='system'")["value"])
    config["limit_type"] = "all"
    conn.execute("update config set value=%s where name='recharge' and type='system'",json.dumps(config))
    conn.commit()

    # tcp系数
    if not conn.fetchone("select * from config where name='tcp_coefficient' "):
        conn.execute("insert into config values ('tcp_coefficient','1.1','system','0','global', now(),now(),1,null); ")
        conn.commit()

    # 日志记录
    if not conn.fetchone("SELECT column_name FROM information_schema.columns WHERE table_name = 'site' AND column_name = 'log_req_header' "):
        conn.execute("alter table site add log_req_header boolean default true after white_time;")
        conn.commit()

    if not conn.fetchone("SELECT column_name FROM information_schema.columns WHERE table_name = 'site' AND column_name = 'log_resp_header' "):
        conn.execute("alter table site add log_resp_header boolean default false after log_req_header;")
        conn.commit()

    if not conn.fetchone("SELECT column_name FROM information_schema.columns WHERE table_name = 'site' AND column_name = 'log_req_body' "):
        conn.execute("alter table site add log_req_body boolean default false after log_resp_header;")
        conn.commit()

    if not conn.fetchone("SELECT column_name FROM information_schema.columns WHERE table_name = 'site' AND column_name = 'log_req_body_max_size' "):
        conn.execute("alter table site add log_req_body_max_size int(11) default 16 after log_req_body;")
        conn.commit()

    if not conn.fetchone("select * from config where name='log_req_header' "):
        conn.execute("insert into config values ('log_req_header','1','site_default_config','0','global', now(),now(),1,null); ")
        conn.commit()

    if not conn.fetchone("select * from config where name='log_resp_header' "):
        conn.execute("insert into config values ('log_resp_header','0','site_default_config','0','global', now(),now(),1,null); ")
        conn.commit()

    if not conn.fetchone("select * from config where name='log_req_body' "):
        conn.execute("insert into config values ('log_req_body','0','site_default_config','0','global', now(),now(),1,null); ")
        conn.commit()

    if not conn.fetchone("select * from config where name='log_req_body_max_size' "):
        conn.execute("insert into config values ('log_req_body_max_size','16','site_default_config','0','global', now(),now(),1,null); ")
        conn.commit()


    config = json.loads(conn.fetchone("select value from config where name='nginx-config-file' and scope_name='global' ")["value"])
    config["http"]["client_body_buffer_size"] = 16
    conn.execute("update config set value=%s where name='nginx-config-file' and scope_name='global' ",json.dumps(config))
    conn.commit()

    # ipv6
    if not conn.fetchone("SELECT column_name FROM information_schema.columns WHERE table_name = 'node_group' AND column_name = 'v4_cname_hostname' "):
        conn.execute("alter table node_group add v4_cname_hostname varchar(255) after cname_hostname;")
        
        # 填充v4_cname_hostname
        rows = conn.fetchall("select id from node_group")
        for row in rows:
            gid = row["id"]
            v4_cname_hostname = ''.join(random.sample("abcdefghjkmnpqrstuvwxyz23456789", 8))
            conn.execute("update node_group set v4_cname_hostname=%s where id=%s", (v4_cname_hostname,gid,))

        conn.commit()

    if not conn.fetchone("SELECT column_name FROM information_schema.columns WHERE table_name = 'node_group' AND column_name = 'need_gen_v4' "):
        conn.execute("alter table node_group add need_gen_v4 boolean default false after v4_cname_hostname;")
        conn.execute("update node_group set need_gen_v4=1 where id in (select distinct node_group_id from line l left join node n on n.id = l.node_ip_id where n.ip like '%%:%%');")
        conn.commit()

    if not conn.fetchone("SELECT column_name FROM information_schema.columns WHERE table_name = 'line' AND column_name = 'v4_task_id' "):
        conn.execute("alter table line add v4_task_id bigint after task_id;")
        conn.commit()

    if not conn.fetchone("SELECT column_name FROM information_schema.columns WHERE table_name = 'site' AND column_name = 'enable_ipv6' "):
        conn.execute("alter table site add enable_ipv6 boolean default true after log_req_body_max_size;")
        conn.commit()

    if not conn.fetchone("SELECT column_name FROM information_schema.columns WHERE table_name = 'stream' AND column_name = 'enable_ipv6' "):
        conn.execute("alter table stream add enable_ipv6 boolean default true after block_region;")
        conn.commit()

    if not conn.fetchone("SELECT column_name FROM information_schema.columns WHERE table_name = 'user_package' AND column_name = 'enable_ipv6' "):
        conn.execute("alter table user_package add enable_ipv6 boolean default true after http3;")
        conn.commit()

    # 增加扣款类型
    conn.execute("update `order` set type='扣款' where amount < 0; ")
    conn.commit()

    # 通知方式
    method_config = json.loads(conn.fetchone("select value from config where name='notify-method'")["value"])
    email = method_config["email"]
    phone = method_config["phone"]

    config = json.loads(conn.fetchone("select value from config where name='traffic-exceed-notify'")["value"])
    config["email"] = email
    config["phone"] = phone
    conn.execute("update config set value=%s where name='traffic-exceed-notify' ", json.dumps(config) )

    config = json.loads(conn.fetchone("select value from config where name='traffic-exceeding-notify'")["value"])
    config["email"] = email
    config["phone"] = phone
    conn.execute("update config set value=%s where name='traffic-exceeding-notify' ", json.dumps(config) )

    config = json.loads(conn.fetchone("select value from config where name='package-expire-notify'")["value"])
    config["email"] = email
    config["phone"] = phone
    conn.execute("update config set value=%s where name='package-expire-notify' ", json.dumps(config) )

    config = json.loads(conn.fetchone("select value from config where name='package-expiring-notify'")["value"])
    config["email"] = email
    config["phone"] = phone
    conn.execute("update config set value=%s where name='package-expiring-notify' ", json.dumps(config) )

    config = json.loads(conn.fetchone("select value from config where name='cert-expire-notify'")["value"])
    config["email"] = email
    config["phone"] = phone
    conn.execute("update config set value=%s where name='cert-expire-notify' ", json.dumps(config) )

    config = json.loads(conn.fetchone("select value from config where name='cert-expiring-notify'")["value"])
    config["email"] = email
    config["phone"] = phone
    conn.execute("update config set value=%s where name='cert-expiring-notify' ", json.dumps(config) )

    config = json.loads(conn.fetchone("select value from config where name='cc-switch-notify'")["value"])
    config["email"] = email
    config["phone"] = phone
    conn.execute("update config set value=%s where name='cc-switch-notify' ", json.dumps(config) )

    config = json.loads(conn.fetchone("select value from config where name='bandwidth-exceed-notify'")["value"])
    config["email"] = email
    config["phone"] = phone
    conn.execute("update config set value=%s where name='bandwidth-exceed-notify' ", json.dumps(config) )

    config = json.loads(conn.fetchone("select value from config where name='conn-exceed-notify'")["value"])
    config["email"] = email
    config["phone"] = phone
    conn.execute("update config set value=%s where name='conn-exceed-notify' ", json.dumps(config) )
    conn.commit()

    # 阿里云短信
    sms_auth = json.loads(conn.fetchone("select value from config where name='sms_config'")["value"])
    if "type" in sms_auth and sms_auth['type'] == "aliyun":
        # 构建auth
        sms_aliyun_access_key_id = sms_auth['sms_aliyun_access_key_id']
        sms_aliyun_access_key_secret = sms_auth['sms_aliyun_access_key_secret']
        sms_aliyun_sign_name = sms_auth['sms_aliyun_sign_name']
        auth = json.dumps({"sms_aliyun_access_key_id":sms_aliyun_access_key_id,"sms_aliyun_access_key_secret":sms_aliyun_access_key_secret,"sms_aliyun_sign_name":sms_aliyun_sign_name})

        # traffic-exceed-notify
        config = json.loads(conn.fetchone("select value from config where name='traffic-exceed-notify'")["value"])
        templ_id = ""
        if "templ-id" in config:
            templ_id = config["templ-id"]

        if templ_id:
            ok, msg = get_templ_content(auth, templ_id)
            if ok:
                config["templ-content"] = msg
                conn.execute("update config set value=%s where name='traffic-exceed-notify' ", json.dumps(config) )
                conn.commit()


        # traffic-exceeding-notify
        config = json.loads(conn.fetchone("select value from config where name='traffic-exceeding-notify'")["value"])
        templ_id = ""
        if "templ-id" in config:
            templ_id = config["templ-id"]

        if templ_id:
            ok, msg = get_templ_content(auth, templ_id)
            if ok:

                config["templ-content"] = msg
                conn.execute("update config set value=%s where name='traffic-exceeding-notify' ", json.dumps(config) )
                conn.commit()


        # package-expire-notify
        config = json.loads(conn.fetchone("select value from config where name='package-expire-notify' ")["value"])
        templ_id = ""
        if "templ-id" in config:
            templ_id = config["templ-id"]

        if templ_id:
            ok, msg = get_templ_content(auth, templ_id)
            if ok:
                config["templ-content"] = msg
                conn.execute("update config set value=%s where name='package-expire-notify' ", json.dumps(config) )
                conn.commit()


        # package-expiring-notify
        config = json.loads(conn.fetchone("select value from config where name='package-expiring-notify'")["value"])
        templ_id = ""
        if "templ-id" in config:
            templ_id = config["templ-id"]

        if templ_id:
            ok, msg = get_templ_content(auth, templ_id)
            if ok:
                config["templ-content"] = msg
                conn.execute("update config set value=%s where name='package-expiring-notify' ", json.dumps(config) )
                conn.commit()


        # cert-expire-notify
        config = json.loads(conn.fetchone("select value from config where name='cert-expire-notify'")["value"])
        templ_id = ""
        if "templ-id" in config:
            templ_id = config["templ-id"]

        if templ_id:
            ok, msg = get_templ_content(auth, templ_id)
            if ok:
                config["templ-content"] = msg
                conn.execute("update config set value=%s where name='cert-expire-notify' ", json.dumps(config) )
                conn.commit()


        # cert-expiring-notify
        config = json.loads(conn.fetchone("select value from config where name='cert-expiring-notify'")["value"])
        templ_id = ""
        if "templ-id" in config:
            templ_id = config["templ-id"]

        if templ_id:
            ok, msg = get_templ_content(auth, templ_id)
            if ok:

                config["templ-content"] = msg
                conn.execute("update config set value=%s where name='cert-expiring-notify' ", json.dumps(config) )
                conn.commit()


        # cc-switch-notify
        config = json.loads(conn.fetchone("select value from config where name='cc-switch-notify'")["value"])
        templ_id = ""
        if "templ-id" in config:
            templ_id = config["templ-id"]

        if templ_id:
            ok, msg = get_templ_content(auth, templ_id)
            if ok:
                config["templ-content"] = msg
                conn.execute("update config set value=%s where name='cc-switch-notify' ", json.dumps(config) )
                conn.commit()


        # bandwidth-exceed-notify
        config = json.loads(conn.fetchone("select value from config where name='bandwidth-exceed-notify'")["value"])
        templ_id = ""
        if "templ-id" in config:
            templ_id = config["templ-id"]

        if templ_id:
            ok, msg = get_templ_content(auth, templ_id)
            if ok:

                config["templ-content"] = msg
                conn.execute("update config set value=%s where name='bandwidth-exceed-notify' ", json.dumps(config) )
                conn.commit()

        # conn-exceed-notify
        config = json.loads(conn.fetchone("select value from config where name='conn-exceed-notify'")["value"])
        templ_id = ""
        if "templ-id" in config:
            templ_id = config["templ-id"]

        if templ_id:
            ok, msg = get_templ_content(auth, templ_id)
            if ok:
                config["templ-content"] = msg
                conn.execute("update config set value=%s where name='conn-exceed-notify' ", json.dumps(config) )
                conn.commit()

except:
    conn.rollback()
    raise

finally:
    conn.close()
EOF

/opt/venv/bin/python /tmp/_db.py



# 更新panel或conf
cd /opt/cdnfly/master/panel;
\cp dashboard/img/{ad.jpeg,favicon.ico,logo.png} /opt/$dir_name/master/panel/dashboard/img;  # 保存logo
rm -rf /opt/cdnfly/master/panel/dashboard # 删除旧的dashboard
\cp -a /opt/$dir_name/master/panel/dashboard /opt/cdnfly/master/panel/ # 复制新的dashboard

flist='master/conf/nginx_global.tpl
master/conf/nginx_http_default.tpl'
for f in `echo $flist`;do
\cp -a /opt/$dir_name/$f /opt/cdnfly/$f
done

# 清理宝塔缓存
rm -rf /www/server/nginx/proxy_cache_dir/*


}

update_file() {
cd /opt/$dir_name/master/
for i in `find ./ | grep -vE "^./$|^./agent$|^./conf$|conf/config.py|conf/nginx_global.tpl|conf/supervisord.conf|conf/supervisor_master.conf|conf/nginx_http_default.tpl|conf/nginx_http_vhost.tpl|conf/nginx_stream_vhost.tpl|conf/ssl.cert|conf/ssl.key|^./panel"`;do
    \cp -aT $i /opt/cdnfly/master/$i
done

}

# 定义版本
version_name="v5.8.1"
version_num="50801"
dir_name="cdnfly-master-$version_name"
tar_gz_name="$dir_name-$(get_sys_ver).tar.gz"

# 下载安装包
cd /opt
echo "开始下载$tar_gz_name..."
download "https://dl2.lotcdn.com/cdnfly/$tar_gz_name" "https://us.lotcdn.com/cdnfly/$tar_gz_name" "$tar_gz_name"
echo "下载完成"

echo "开始解压..."
rm -rf $dir_name
tar xf $tar_gz_name
echo "解压完成"

cd /opt
echo "准备升级数据库..."
upgrade_db
echo "升级数据库完成"

echo "更新文件..."
update_file
echo "更新文件完成." 

echo "修改config.py版本..."
sed -i "s/VERSION_NAME=.*/VERSION_NAME=\"$version_name\"/" /opt/cdnfly/master/conf/config.py
sed -i "s/VERSION_NUM=.*/VERSION_NUM=\"$version_num\"/" /opt/cdnfly/master/conf/config.py
rm -f /opt/cdnfly/master/conf/config.pyc
echo "修改完成"

echo "开始重启主控..."
supervisorctl  -c /opt/cdnfly/master/conf/supervisord.conf restart all
#supervisorctl  -c /opt/cdnfly/master/conf/supervisord.conf reload
echo "重启完成"

echo "清理文件"
rm -rf /opt/$dir_name
rm -f /opt/$tar_gz_name
echo "清理完成"

echo "完成$version_name版本升级"