# !/usr/bin/env bash
    

set -e

scope="prod"

timestamp="0"

doc_url="https://open.feishu.cn/open-apis/bitable/v1/apps/bascn23jXkaikyNiXD30koaV8Vb/tables/tblSghhiGSQSY3D5/records"

token="t-1d582b81a4149d5f908323bea99044fa5d6f759d"

mysql_command="mysql -ustaging -htidb.e23bdccc.cb17aaf2.us-west-2.prod.aws.tidbcloud.com -P4000 -pZqfjTO5G_CJx%AdiqFuyVS6P staging_central"

countrycode_file="/tmp/fileforcountrycode_doc_test"

new_user_sql="select 
    t.country, t.id,t.name,t.alias
from 
    tenants t  
limit 3" 

count="0"

alert_url="https://open.feishu.cn/open-apis/bot/v2/hook/6aed0f4e-f7f1-4223-b5a3-d503e7100587"

template_color="blue"

if [ "$scope" == "test" ]
then
    result_json="/tmp/docjsonresult_test.json"
    temp_sql_result="/tmp/tempsqlresult_test"
    template_json="/tmp/templatejson_test.json"
    doc_url="https://open.feishu.cn/open-apis/bitable/v1/apps/bascn23jXkaikyNiXD30koaV8Vb/tables/tblSghhiGSQSY3D5/records"
    mysql_command="mysql -ustaging -htidb.e23bdccc.cb17aaf2.us-west-2.prod.aws.tidbcloud.com -P4000 -pZqfjTO5G_CJx%AdiqFuyVS6P staging_central"
    new_user_sql="select 
        t.country, t.id,t.name,t.alias
    from 
        tenants t  
    limit 3" 
    user_count_sql="select 
        count(*)
    from
        tenants"
    user_count="385"
    countrycode_file="/tmp/fileforcountrycode_doc_test"
    template_color="green"
    alert_json="/tmp/num_dec_alert_test.json"
elif [ "$scope" == "prod" ]
then
    result_json="/tmp/docjsonresult_prod.json"
    temp_sql_result="/tmp/tempsqlresult_prod"
    template_json="/tmp/templatejson_prod.json"
    doc_url="https://open.feishu.cn/open-apis/bitable/v1/apps/bascnrc0e3hncD6ZSgY2Pd6wf4g/tables/tblMiQzeksh383z1/records"
    mysql_command="mysql -h metadb-tidb -P 4000 dbaas"
    countrycode_file="/tmp/fileforcountrycode_doc_prod"
    new_user_sql="select 
        t.country, t.id,t.name,t.alias
    from 
        tenants t  
    WHERE 
        (not lower(t.name) like '%pingcap%' ) and  t.plan = 'poc' and t.kind = 'external' and t.status = 'active' And t.updated_at >= TIMESTAMP_TAG_LEFT and t.updated_at < TIMESTAMP_TAG_RIGHT and t.kind = 'external';"
    user_count_sql="select
        count(*)
    from
        tenants t
    where
        (not lower(t.name) like '%pingcap%' ) and  t.plan = 'poc' and t.kind = 'external' and t.status = 'active';"
    user_count="24"
    template_color="red"
    alert_json="/tmp/num_dec_alert_prod.json"
fi


cat > $template_json <<EOF
{ 
    "fields": {
        "Current Status": "In Progress",
        "Customer": "CUSTOMER_NAME_TAG",
        "Escalation Owner": [
            {
                "email": "fan.wang@pingcap.com",
                "en_name": "Fan Wang",
                "id": "ou_263021c09e1a6265a8feb2deda8e1b5c",
                "name": "Fan Wang"
            }
        ],
        "Region": "REGION_TAG"
    }
}
EOF

cat > $alert_json <<EOF
{ 
    "msg_type": "interactive",
    "card":
    {
        "config": {
            "wide_screen_mode": true
        },
        "header": {
            "template": "red",
            "title": {
                "content": "Doc updater",
                "tag": "plain_text"
            }
        },
        "elements": [
            {
                "tag": "markdown",
                "content": "Number of tenants decreased <at id=all></at>"
            }
        ]
    }
}
EOF

cat > $countrycode_file <<EOF
    AD,EMEA
    AE,EMEA
    AF,EMEA
    AG,US
    AI,US
    AL,EMEA
    AM,EMEA
    AO,EMEA
    AQ,EMEA
    AR,US
    AS,Apac
    AT,EMEA
    AU,Apac
    AW,US
    AX,EMEA
    AZ,EMEA
    BA,EMEA
    BB,US
    BD,Apac
    BE,EMEA
    BF,EMEA
    BG,EMEA
    BH,EMEA
    BI,EMEA
    BJ,EMEA
    BL,EMEA
    BM,US
    BN,Apac
    BO,US
    BR,US
    BS,US
    BT,Apac
    BV,EMEA
    BW,EMEA
    BY,EMEA
    BZ,US
    CA,US
    CC,Apac
    CD,EMEA
    CF,EMEA
    CG,EMEA
    CH,EMEA
    CI,EMEA
    CK,EMEA
    CL,US
    CM,EMEA
    CN,China Outbound
    CO,US
    CR,US
    CU,US
    CV,EMEA
    CW,EMEA
    CX,Apac
    CY,EMEA
    CZ,EMEA
    DE,EMEA
    DJ,EMEA
    DK,EMEA
    DM,US
    DO,US
    DZ,EMEA
    EC,US
    EE,EMEA
    EG,EMEA
    EH,EMEA
    ER,EMEA
    ES,EMEA
    ET,EMEA
    FI,EMEA
    FJ,Apac
    FK,US
    FM,Apac
    FO,EMEA
    FR,EMEA
    GA,EMEA
    GB,EMEA
    GD,US
    GE,EMEA
    GF,EMEA
    GG,EMEA
    GH,EMEA
    GI,EMEA
    GL,EMEA
    GM,EMEA
    GN,EMEA
    GP,EMEA
    GQ,EMEA
    GR,EMEA
    GS,US
    GT,US
    GU,Apac
    GW,EMEA
    GY,US
    HK,Apac
    HM,EMEA
    HN,US
    HR,EMEA
    HT,US
    HU,EMEA
    ID,Apac
    IE,EMEA
    IL,EMEA
    IM,EMEA
    IN,Apac
    IO,Apac
    IQ,EMEA
    IR,EMEA
    IS,EMEA
    IT,EMEA
    JE,EMEA
    JM,US
    JO,EMEA
    JP,Japan
    KE,EMEA
    KG,EMEA
    KH,Apac
    KI,Apac
    KM,EMEA
    KN,US
    KP,Apac
    KR,Apac
    KW,EMEA
    KY,US
    KZ,EMEA
    LA,Apac
    LB,EMEA
    LC,US
    LI,EMEA
    LK,Apac
    LR,EMEA
    LS,EMEA
    LT,EMEA
    LU,EMEA
    LV,EMEA
    LY,EMEA
    MA,EMEA
    MC,EMEA
    MD,EMEA
    ME,EMEA
    MF,EMEA
    MG,EMEA
    MH,Apac
    MK,EMEA
    ML,EMEA
    MM,Apac
    MN,Apac
    MO,Apac
    MP,Apac
    MQ,EMEA
    MR,EMEA
    MS,US
    MT,EMEA
    MU,EMEA
    MV,Apac
    MW,EMEA
    MX,US
    MY,Apac
    MZ,EMEA
    NA,EMEA
    NC,EMEA
    NE,EMEA
    NF,Apac
    NG,EMEA
    NI,US
    NL,EMEA
    NO,EMEA
    NP,Apac
    NR,Apac
    NU,Apac
    NZ,Apac
    OM,EMEA
    PA,US
    PE,US
    PF,EMEA
    PG,Apac
    PH,Apac
    PK,Apac
    PL,EMEA
    PM,EMEA
    PN,Apac
    PR,US
    PS,EMEA
    PT,EMEA
    PW,Apac
    PY,US
    QA,EMEA
    RE,EMEA
    RO,EMEA
    RS,EMEA
    RU,EMEA
    RW,EMEA
    SA,EMEA
    SB,Apac
    SC,EMEA
    SD,EMEA
    SE,EMEA
    SG,Apac
    SH,EMEA
    SI,EMEA
    SK,EMEA
    SL,EMEA
    SM,EMEA
    SN,EMEA
    SO,EMEA
    SR,US
    SS,EMEA
    ST,EMEA
    SV,US
    SX,EMEA
    SY,EMEA
    SZ,EMEA
    TC,US
    TD,EMEA
    TF,EMEA
    TG,EMEA
    TH,Apac
    TJ,EMEA
    TK,Apac
    TL,Apac
    TM,EMEA
    TN,EMEA
    TO,Apac
    TR,EMEA
    TT,US
    TV,Apac
    TW,Apac
    TZ,EMEA
    UA,EMEA
    UG,EMEA
    UM,Apac
    US,US
    UY,US
    UZ,EMEA
    VA,EMEA
    VC,US
    VE,US
    VG,US
    VI,US
    VN,Apac
    VU,Apac
    WF,EMEA
    WS,Apac
    YE,EMEA
    YT,EMEA
    ZA,EMEA
    ZM,EMEA
    ZW,EMEA
EOF
echo something

appendRegionInfo() {
# head -n 5 $countrycode_file

    while  IFS= read -r  line
    do
        country=$(echo "$line" | cut -f1)
        # country="SG"
        if [ -z "$country" ];
        then
            region="null"
        else
            region="$(grep -i "$country," $countrycode_file | sed 's/^[ \t]*//g' | awk -F ',' '{print $2}')"
            if [ -z "$region" ];
            then 
                region="null"
            fi
        fi
        echo "$line" | awk -F "\t" -v OFS="\t" "{\$1=\"$region\";print \$0 }"   
    done
}

getTokenJson() {
    curl -d '{"app_id":"cli_a2b00226a83dd00c", "app_secret":"1YB8MlkJHc52VYIVpDiJAfwayhVVLwD4"}'\
            -H "Content-Type: application/json" \
            -X POST "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal" | \
            tr -d '{}"' | cut -d, -f4 | cut -d: -f2
    
}

setUpToken() {
    new_timestamp="$(date +%s)"
    echo new_timestamp
    if [[ $(($new_timestamp - $timestamp)) -gt 5400 ]]; then
        token="$(getTokenJson)"
        echo $token
        timestamp="$new_timestamp"
    fi
}

generateJson() {
    sed "s/REGION_TAG/$1/" $template_json | sed "s/CUSTOMER_NAME_TAG/$2/" 
}

preprocess() {
    while IFS= read -r line
    do
        echo "$line" | sed "s/TIMESTAMP_TAG_LEFT/'$1'/" | sed "s/TIMESTAMP_TAG_RIGHT/'$2'/"
    done
}

old_ts="$(date -u '+%Y-%m-%d %T')"

while true; do
    new_ts="$(date -u '+%Y-%m-%d %T')"
    # echo "$temp_sql_result"
    new_count=$(echo "$user_count_sql" | $mysql_command | awk 'NR==2')
    echo "new count = $new_count"
    if [[ "$new_count" -gt "$user_count" ]]
    then
        echo "$new_user_sql" | preprocess "$old_ts" "$new_ts" | $mysql_command | appendRegionInfo | awk -F "\t" 'NR!=1{printf "%s,%s\n", $1, $3}' > "$temp_sql_result"
        cat "$temp_sql_result"
        if [ -s "$temp_sql_result" ]
        then
            while IFS= read -r line
            do
                region_info="$(echo "$line" | cut -d, -f1)"
                tenant_name_info="$(echo "$line" | cut -d, -f2)"
                generateJson "$region_info" "$tenant_name_info" > $result_json
                setUpToken
                cat $result_json
                curl -X POST -d @"$result_json" -H "Content-Type: application/json; charset=utf-8" -H "Authorization:Bearer $token" "$doc_url"
                sleep 1
            done < "$temp_sql_result"
        fi
    elif [[ "$new_count" -lt "$user_count" ]]
    then
        curl -XPOST -H "Content-Type: application/json" $alert_url  -d @$alert_json
    else 
        echo "Still equal"
    fi
    old_ts="$new_ts"
    user_count="$new_count"
    sleep 900
done