#!/bin/bash

source ~/.gamerc

export LC_ALL=C

[ "$1" == "" ] && BAN_MINUTES=30 || BAN_MINUTES="$1"

sendscript allwz -o nosave <<< "get_log_filter $(date -d "-1 day" +%Y%m%d) now Zone Message" \
|egrep -v "TEAM:|Send|BroadcastDeclaration|GM Cmd|:[SsBb]>|FAMILY:|ROSCA:"\
|sort -r -k 2 -t , |head -100000 > ~/message

KEYWORDS="$(awk -F'\\] \\[[A-Z]+:' '{print $NF}' ~/message|awk -F'\\] to \\[' '{print $1}'|LC_ALL=C sed 's/^.\{8,10\}\(.*\).\{8,10\}/\1/g'|sort|LC_ALL=C uniq -c|sort -g|awk '$1 > 80'|LC_ALL=C sed 's/^.........//g;s/[^a-zA-Z0-9]/./g'|LC_ALL=C sed -n '/^.\{20,\}$/p'|sed 's/^\(.\{,20\}\).*/\1/g'|tr '\n' '|'|sed 's/|$//g')"

[ "$KEYWORDS" == "" ] && exec echo "No spammer found."

LC_ALL=C egrep --color "$KEYWORDS" ~/message |LC_ALL=C sed 's/.*LIFE:\([^,]\+\),.*/\1/g'|sort|uniq > ~/goldspammer

echo
echo -e "\n\n\n\n\n$(date +"%Y%m%dT%H%M%S"), Start banning goldspammers for $BAN_MINUTES minutes ... " \
| colorize green | tee -a ~/ban_goldspammer.log

for CHAR in `cat ~/goldspammer`;do

        echo
        grep LIFE:$CHAR, ~/message|LC_ALL=C egrep --color "$KEYWORDS"|tail -2| colorize cyan

        echo -n "$CHAR($(grep LIFE:$CHAR, ~/message|LC_ALL=C egrep --color "$KEYWORDS"|wc -l) times): "  | colorize yellow
        SERVERID="$(ssh accountdb member_db <<< "copy (select serverid from currentuser where strcharid='$CHAR') to stdout csv;")"
        CHARID="$(ssh accountdb member_db <<< "copy (select char_id from currentuser where strcharid='$CHAR') to stdout csv;")"
        if [ "$SERVERID" == "" ] ; then
                echo OFFLINE | colorize red
                continue
        fi

        EXTIP="$(ssh accountdb member_db <<< "copy (select serverip from currentuser where strcharid='$CHAR') to stdout csv;")"
        SET="$(get_set $SERVERID)"
        CH="$(get_ch $SERVERID)"
        CGI_IP="$(ssh wz$SET$CH "source ~/.gamerc;another_ip $EXTIP")"
        CGI_PORT="$(ssh $CGI_IP "cat server*/ZoneServer$SET$CH/setup.ini|awk -F= '/CGIPort/{print \$2}'")"

        #BAN_RESULT="$(curl -s http://127.0.0.1/cgi-bin/CGIAgent.fcgi?$CGI_IP,$CGI_PORT,$CGI_KEY,ban+$CHAR+$BAN_MINUTES+goldspammer)"
        BAN_RESULT="$(curl -s http://127.0.0.1/cgi-bin/CGIAgent.fcgi?$CGI_IP,$CGI_PORT,$CGI_KEY,channel_limit+$CHARID+$BAN_MINUTES)"

        if grep -q "DONE" <<< "$BAN_RESULT" ; then
                echo "BANNED" | colorize green
                searchplayer $CHAR
                ACCOUNT_NAME="$(get_account_name $SET $CHAR)"
#               echo -n "Force logout: "
#               echo "copy (select char_logout('$ACCOUNT_NAME', 0, 0)) to stdout csv;" | psql -h accountdb $MEMBER_DB_NAME | highlight - 2 1
        else
                echo "FAILED TO BAN" | colorize red
        fi

done | tee -a ~/ban_goldspammer.log

echo -e "\nKeywords:" | colorize purple | tee -a ~/ban_goldspammer.log
tr '|' '\n' <<< "$KEYWORDS" | sed "s/^/$(date +%Y%m%dT%H%M)_KEYWORD:/g"| colorize green | tee -a ~/ban_goldspammer.log
