#!/bin/bash
  
set -e
set -x

SYS=$1
ENV=$2

if [ $# != 2 ]
then
    echo "need tow parameters![gm/alpha prod/dev/test]"
    exit
fi

if [[ "$ENV" == "dev" || "$ENV" == "test" ]];then
    MYSQL_USER="work"
    MYSQL_PASSWORD="Gengmei123"
    MYSQL_HOST="rm-2zeaut61u9sm21m0b.mysql.rds.aliyuncs.com"
    MYSQL_DB="alpha"
    DINGDING='https://oapi.dingtalk.com/robot/send?access_token=47c7de55db1234c6ee0d8f61abae8bc54591f3cef438a41905a0bf4fa33dd6cf'
else
    if [[ "$SYS" == "alpha" ]]
    then
        MYSQL_USER="work"
        MYSQL_PASSWORD="oars152!traipseize738"
        MYSQL_HOST="172.17.40.144"
        MYSQL_DB="alpha"
        DINGDING='https://oapi.dingtalk.com/robot/send?access_token=53686301db86625c308a837fd6d26f56629fc69e693d21b0b12499ab54e74805'
    else
        MYSQL_USER="work"
        MYSQL_PASSWORD="BJQaT9VzDcuPBqkd"
        MYSQL_HOST="172.16.30.143"
        MYSQL_DB="zhengxing"
        DINGDING='https://oapi.dingtalk.com/robot/send?access_token=53686301db86625c308a837fd6d26f56629fc69e693d21b0b12499ab54e74805'
    fi
fi


function red() {
    RED='\033[0;31m'
    NC='\033[0m' # No Color
    printf "${RED} $1 ${NC} \n"
}


LAST_RESULT_FILE="last_total_num.txt"
last_total_num=0
if [[ -e $LAST_RESULT_FILE ]];then
        last_total_num=`cat $LAST_RESULT_FILE`
fi

SQL="select count(1) from api_wordrelsynonym"
results=(`mysql -h $MYSQL_HOST -u $MYSQL_USER -p$MYSQL_PASSWORD $MYSQL_DB -e "$SQL"`)
new_total_num=${results[1]}

echo "new_total_num:"$new_total_num
echo "last_total_num:"$last_total_num

linestoskip=1
Counter=0
FILE="dynamic_synonym.txt"
DICFILE="dynamic_synonym.dic"

if [[ $last_total_num != $new_total_num ]];then
    echo "begin generate dynamic file..."
    if [[ -e $FILE ]];then
            rm -f $FILE
    fi

    if [[ -e $DICFILE ]];then
            rm -f $DICFILE
    fi

    SQL="SELECT GROUP_CONCAT(word SEPARATOR ',') FROM api_wordrelsynonym GROUP BY wordrel_id"
    mysql -h $MYSQL_HOST -u $MYSQL_USER -p$MYSQL_PASSWORD $MYSQL_DB -e "$SQL" | while IFS= read -r ROW
    do
        if [[ $Counter -ge $linestoskip ]]; then
            echo "$ROW" >> $FILE
            array=(${ROW//,/ })
            for var in ${array[@]}
            do
                echo "$var" >> $DICFILE
            done
        fi
        Counter=`expr $Counter + 1`
    done

    echo $new_total_num > $LAST_RESULT_FILE
fi


