#!/bin/bash

function isAlarm()
{
  alarmDescrption=$1
  alarmFile=$2
  alarmDate=`date`
  curl 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=ddea3f5f-fbfc-4c21-994a-71e9fc50e4ef' \
     -H 'Content-Type: application/json' \
     -d '
     {
        "msgtype": "markdown",
        "markdown": {
            "content": "**'"$alarmDescrption"'**\n
            > 错误文件：<font color=\"warning\">'"$alarmFile"'生成错误，请立即查看</font>
            > 告警时间：<font color=\"warning\">'"$alarmDate"'</font>"
        }
     } ' > /dev/null 2>&1
}

function domain_list() {
    # ----------------------------------------------------------------------------------------
    # 获取平台全量域名信息
    let count=0
    while [[ $count -lt 3 ]]; do
        curl 'https://bs.ctcdn.cn/api/v3/manageDomain/export' -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOjI1NH0.9Zw66R0R85avd92qzO-3KQ4DJ2zYXL4ght5bH41iTfA' -H 'content-type: application/json;charset=UTF-8' -vo $data/domain.list > $data/domain.list.response 2>&1

        # 判断响应是否200
        line_number=`cat $data/domain.list | wc -l`
        cat $data/domain.list.response | grep -Eq 'HTTP/(1.1|2) 200 OK'
        if [[ $? -ne 0 || $line_number -lt 20000 ]]; then
            count=$((count+1))
        else
            exit
        fi
    done
    isAlarm '【严重】获取全量域名信息失败' 'domain.list'
    exit 248
}

function renew_backup() {
    cd $data
    lakes_bak > $data/lakes
    curl -so $data/ip.group  "http://150.223.254.77:5044/download/ip.group"

    # backups
    cd $toolbox
    [[ -d '/home/fanmf11/.backups/' ]] && rm -rf /home/fanmf11/.backups/*.tgz || mkdir '/home/fanmf11/.backups/'
    cd $toolbox & bt=$(date +%Y%m%d%H%M%S)
    # cp $data/lakes $data/lakes-$(date +%d)
    # cp $data/ip.group $data/ip.group-$(date +%d)
    tar -czf /home/fanmf11/.backups/toolbox-${bt}.tgz ./*

    [[ ! -s $data/lakes ]] && isAlarm '【严重】基础文件生成错误告警' 'lakes'
    [[ ! -s $data/ip.group ]] && isAlarm '【严重】基础文件生成错误告警' 'ip.group'
    [[ ! -s $backups/toolbox-${bt}.tgz ]] && isAlarm '备份失败告警' "toolbox-${bt}.tgz"
}



function view_check() {
	maps=`cat $data/maps`
	> $data/area.new
	for map in $maps; do
		getlastcover $map > $map
		cat $map | awk '{print $3}' | sed '1d' | sort | uniq >> $data/area.new
		rm $map
	done
	news=`cat $data/area.new | sort | uniq`
	olds=`cat $data/area | awk '{print $1}' | sort | uniq`
    > $data/area.new
    > $data/area.diff
    for new in $news; do
        [[ $new == 'find' ]] && continue
        echo $new >> $data/area.new
        echo $olds | grep -wq $new
        [[ $? -ne 0 ]] && { isAlarm '有新的View需要添加' "$new"; echo $new >> $data/area.diff; sleep 1; }
    done
}

data='/usr/local/script/fanmf11/data'
host=`whoami`
toolbox='/usr/local/script/fanmf11'
backups='/home/fanmf11/.backups'


[[ $1 == '--renew_backup' ]] && renew_backup
[[ $1 == '--domain_list' ]] && domain_list
[[ $1 == '--new_area' ]] && view_check



