#!/bin/bash
# set -e
# bug-1: can not find the configuration of live domain
# usage
function usage {
  echo -e "${c_bc}获取域名详细配置或者对比两个域名的配置异同：${c_e}"
  echo -e "  config -c domain"
  echo -e "  config -d domain_1 domain_2\n"
  exit 100
}

function onCtrlC () {
  # while capture Ctrl+C, kill all background processes silently and exit
  exec 3>&2          # 3 is now a copy of 2
  exec 2> /dev/null  # 2 now points to /dev/null
  kill ${bg_pids} ${progress_pid} >/dev/null 2>&1
  sleep 1            # sleep to wait for process to die
  exec 2>&3          # restore stderr to saved
  exec 3>&-          # close saved version
  echo
  echo -e "${c_bir}Ctrl+C is captured, exiting...\n${c_e}"
  exit 1
}

function get_config {
    # 判断要查询的域名是否在平台，domain.list文件每小时更新一次 -- task.sh
    res=`cat $data/domain.list | grep -w "$domain"`
    if [[ $res == '' ]]; then
        echo -e "${c_br}该域名[$domain]未在天翼平台配置，一个小时内新增的域名无法查询，退出...${c_e}"
        echo -e "${c_br}只接收一个参数，请输入要查询的域名\ne.g. infos www.ctyun.cn\n${c_e}"
        exit 247
    fi
    # ----------------------------------------------------------------------------------------
    # 获取域名信息 - part 1
    curl "https://dcp.ctcdn.cn/traffic-control-api/v2/access/list?access_version_id=1&domain=$domain" -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOjYzfQ.XZ_nNtRWoBRcPBM-bHAG_ciohkNh69n4AVHwV755r6Q' -H 'content-type: application/json;charset=UTF-8' -vo domain_info_1.log > domain_info_1.response 2>&1

    # 判断响应是否200
    cat $trash/domain_info_1.response | grep -Eq 'HTTP/(1.1|2) 200 OK'
    [[ $? -ne 0 ]] && { echo -e "${c_br}获取域名信息-part 1失败，退出...${c_e}"; exit 246; }

    python3 /usr/local/script/fanmf11/get_infos.py --map_info domain_info_1.log $domain
    [[ $? -ne 0 ]] && { echo -e "${c_br}处理域名-part 1信息失败，退出...${c_e}"; exit 242; }

    accid=`cat info.log | awk -F ':' '$1==3 {print $2}'`
    # ----------------------------------------------------------------------------------------
    # 获取域名信息 -- CDN
    curl "https://confmanager.ctcdn.cn/v1/domain/conf/query_union?precise_query=1&domain=$domain" -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOjQxNn0.KEFh_yg3J1y8sL7s3X_8jIR8GGq88A89b7J5YhVYVf8' -H 'content-type: application/json;charset=UTF-8' -vo domain_info_4.log > domain_info_4.response 2>&1

    # 判断响应是否200
    cat $trash/domain_info_4.response | grep -Eq 'HTTP/(1.1|2) 200 OK'
    [[ $? -ne 0 ]] && { echo -e "${c_br}获取域名信息-part 4失败，退出...${c_e}"; exit 243; }

    python3 /usr/local/script/fanmf11/get_infos.py --domain_config_cdn domain_info_4.log $accid $domain
    r_code=$?
    if [[ $r_code -eq 204 ]]; then
        # ----------------------------------------------------------------------------------------
        # 获取域名信息 - live
        curl "https://lasc-new.ctcdn.cn/v1/domain/conf/op_query_union?page_size=20&page=1&domain=$domain" -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOjE4NH0.1Pgfnky-grT0MN2ic04PqMf32BdnF6iN_PMk3kNOzjY' -H 'content-type: application/json;charset=UTF-8' -vo domain_info_5.log > domain_info_5.response 2>&1

        # 判断响应是否200
        cat $trash/domain_info_5.response | grep -Eq 'HTTP/(1.1|2) 200 OK'
        [[ $? -ne 0 ]] && { echo -e "${c_br}获取域名信息-part 5失败，退出...${c_e}"; exit 235; }

        python3 /usr/local/script/fanmf11/get_infos.py --domain_info_5 domain_info_5.log $accid
        [[ $? -ne 0 ]] && { echo -e "${c_br}处理域名-part 5信息失败，退出...${c_e}"; exit 237; }

        # ----------------------------------------------------------------------------------------
        # 获取域名信息 - part 6
        domain_id=`cat info.log | awk -F ':' '$1==4 {print $2}'`
        curl "https://lasc-new.ctcdn.cn/v1/domain/internal/domain_config?domain_id=$domain_id" -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOjE4NH0.1Pgfnky-grT0MN2ic04PqMf32BdnF6iN_PMk3kNOzjY' -H 'content-type: application/json;charset=UTF-8' -vo domain_info_6.log > domain_info_6.response 2>&1

        # 判断响应是否200
        cat $trash/domain_info_6.response | grep -Eq 'HTTP/(1.1|2) 200 OK'
        [[ $? -ne 0 ]] && { echo -e "${c_br}获取域名信息-part 6失败，退出...${c_e}"; exit 238; }

        python3 /usr/local/script/fanmf11/get_infos.py --domain_config_live domain_info_6.log $domain
        [[ $? -ne 0 ]] && { echo -e "${c_br}处理域名-part 6信息失败，退出...${c_e}"; exit 236; }

    elif [[ $r_code -ne 0 ]]; then
        echo -e "${c_br}处理域名-part 4信息失败，退出...${c_e}"
        exit 239
    else
        :
    fi
}


# Self defined color shortcut
c_br='\e[1;31m'     # bold red
c_bg='\e[1;32m'     # bold green
c_by='\e[1;33m'     # bold yellow
c_bb='\e[1;34m'     # bold blue
c_bp='\e[1;35m'     # bold purple
c_bc='\e[1;36m'     # bold cyan
c_bir='\e[1;3;31m'  # bold italic red
c_bib='\e[1;3;34m'  # bold italic blue
c_bic='\e[1;3;36m'  # bold italic cyan
c_e='\e[0m'         # reset
# some initialization
stty erase '^H'  # allow backspace
data='/usr/local/script/fanmf11/data'
toolbox='/usr/local/script/fanmf11/'
OP="prefix "$@
dash=`echo $OP | awk '{print $2}'`
first=`echo $OP | awk '{print $3}'`
second=`echo $OP | awk '{print $4}'`
flg=1    # signify if rip is acquired successfully or not, 0 - OK and 1 -NG
TS=`date +%s%N`
host=`whoami`
trash="/usr/local/script/fanmf11/trash/$host/$TS"

if [[ -d $trash ]]; then
    echo -e "${c_br}对于同一个用户，同一时间只能运行一个实例，请重新运行...${c_e}"
    exit 245
else
    mkdir -p $trash
    cd $trash && cd ..
    docs=`ls`
    for doc in $docs; do
        [[ -f $doc ]] && rm -rf $doc
    done
    folders=`ls -t`
    while [[ `echo $folders | awk '{print NF}'` -gt 29 ]]; do
        folder=`ls -t | tail -1`
        rm -rf $folder
        folders=`ls -t`
    done
    cd $trash && touch config
fi
# set a trap for Ctrl+C
trap 'onCtrlC' INT


if [[ $# -eq 2 && $dash == '-c' ]]; then
    domain=$first
    get_config
    exec 3>&2 && exec 2> log.json
    cat $domain | tr -d ' ' | sed 's/"{/{/g' | sed 's/}"/}/g' | sed 's/\\"/"/g' | sed 's/\\n/ /g' | sed 's/\\t//g'| jq -r . | awk -f $toolbox/reformat.awk | jq -r . > log.json 2>&1
    cat log.json | grep -q 'parse error'
    [[ $? -eq 0 ]] && { cat $domain | jq -r .; } || { cat log.json | jq -r .; }
    exec 2>&3 && exec 3>&-

elif [[ $# -eq 3 && $dash == '-d' ]]; then
    domain=$first
    get_config
    exec 3>&2 && exec 2> log.json
    cat $domain | tr -d ' ' | sed 's/"{/{/g' | sed 's/}"/}/g' | sed 's/\\"/"/g' | sed 's/\\n/ /g' | sed 's/\\t//g'| jq -S . | awk -f $toolbox/reformat.awk | jq -S . > log.json 2>&1
    cat log.json | grep -q 'parse error'
    [[ $? -eq 0 ]] && { cat $domain | jq -S -f $toolbox/normalize.jq > first.json; }
    jq -S -f $toolbox/normalize.jq log.json > first.json
    exec 2>&3 && exec 3>&-
    domain=$second
    get_config
    exec 3>&2 && exec 2> log.json
    cat $domain | tr -d ' ' | sed 's/"{/{/g' | sed 's/}"/}/g' | sed 's/\\"/"/g' | sed 's/\\n/ /g' | sed 's/\\t//g'| jq -S . | awk -f $toolbox/reformat.awk | jq -S . > log.json 2>&1
    cat log.json | grep -q 'parse error'
    [[ $? -eq 0 ]] && { cat $domain | jq -S -f $toolbox/normalize.jq > second.json; }
    jq -S -f $toolbox/normalize.jq log.json > second.json
    exec 2>&3 && exec 3>&-
    jaydiff --json --indent='  ' --slice-myers first.json second.json
    echo -e "${c_bic}此对比结果仅供参考，由于不同结构的JSON数据语义可能是相同的。${c_by}可以仔细对比下显示不同的部分，有可能是因为结构不同造成的。${c_bic}另外，可以用JSON在线对比工具做进一步检查如下文件${c_e}"
    echo -e "${c_bib}  `pwd`/first.json${c_e}"
    echo -e "${c_bib}  `pwd`/second.json${c_e}\n"
else
    usage
fi

