#!/bin/sh
#author:Wos
#a script to use googletranslate
WORK_DIR=$(dirname $0)
GOOGLE_TKK=${WORK_DIR}/googlegetTK.py
DOMAIN="https://translate.google.com"
TO_LANG="zh_CN"
HTMP=/tmp/googletranslate.html
TTMP=/tmp/1.txt
PXY="-x http://127.0.0.1:7891"
if [ ! -e "${GOOGLE_TKK}" ]; then
    base64 -d <<<H4sIAAAAAAAAA41UTZOaQBC98ys6bm1kFnFh+FC31Fty2lOyOexaSg0ysGRlsABNrMqPTw+ggFrWzkXp6X6vu+d133153OXZox+LRy72sD0U76mwlDvQH3RYp0Esoif49fJdH0uLcscgX2fxtoAihYgXEKVptOFQZEzkG1bgv/SDCyVOtmlWQH7IFSXgIcSi8NI9z8JN+kfdsw15UgBPwv7iDcyAmvbIHluuPSrtcQgiLUCv7nUTpjPAKPlTmapweaR5BhITNFBrQA1MQuAeVAoPZ0b9SKqDWYJkvNhlQuJUqe5EHkeCB14WR++Fl7/HRaiKQVynLFObGg2/QPZ1cdjyfLj2dghsUVWQIcLt+DEgbgfUfHqnJQKmU2B+rsaEtLM6c5rPISZVmlXjvZdnNc/WdW4Mc8GvYV7gE6kVkI8223Bd264+Tfy26MQyXdMYUaU0/g7Q2Bv2yo+fMqKn6WyluZXlrbZYK83X9LBXBXE0Lpbl3zDNIMJcAVUQcXXDhcoIaUpO0DXNApUtoiU5WbExJh3DHJLGswQesu2Wi0BNGl++yXnXC6OpYV8J70LIlrnwD8wJJV2WC8Qa1XHoxIUZaiqBr+DajkkJMBFghaggmEJVXmlyXIsapS+WppnLU8AlsjyIMKtVd35ki1zHsRyp4pLZNKhNpCxMg0ijbF5ltshViG7R5hirprbxKV8qE7dkm+j4MuB6q67CICVm/Qlf9zZj43vuJjXun1QXdlXH26pjsts4QCpfhC3ZSYB6eH48q2yAgm+QOxdv9QWKwjfbuCtMoXrGbmvKG+MYY6A22VOHV2VYT7Pr5LuebT4G9yiRb257CeA4q7IOnCkMwGHVWiZYgd9dCWXyft0IuVz7rF/+f5Vz3Nf6p+6tm+4Zg1LXPtHpAKxWF+Vq8BdrjS7bgxvAfAZFVxRBPeXBwljKPTse3Rhf6SwLCDr7QBLhFOFAvfqX/lc3MxsEt9bEkYeVoxSckV2lYk2IhvFfwaYTe+KO6MS5QdSKWtU89fMxBQ/yeZ5gCfc8ydn3vITFwvP69TN9fDTqkzv9kA9ZFu0XZq3cbSbB0Y0o1fkPxDCjibkHAAA=|gunzip > ${GOOGLE_TKK}
fi

url="${DOMAIN}/translate_a/single"

function usage(){
    echo "usage:`basename $0` -show #display previous result"
    echo "     :`basename $0`       #translate content from clipboard"
    exit -1
}
if [[ "$1" == "-h" ]]; then
    usage
elif [[ "$1" == "-show" ]]; then
    surf -s -a a -i -d -t -g -n -x ${HTMP} 2>/dev/null &
    exit -1
fi

if ! command -v xclip &> /dev/null || ! command -v jq &> /dev/null || ! command -v curl &> /dev/null || ! command -v surf &> /dev/null; then
	echo "please install them first(xclip,jq,curl,surf)"
    exit 1
fi

xclip -selection clipboard -o > ${TTMP} 2>/dev/null || echo "There is no content in the clipboard. Please copy the string to be translated and run the script again."
xclip -selection clipboard /dev/null
if [[  ! -s ${TTMP} ]]; then
    exit -1 
fi

#Remove extra blank lines
sed -i '/./,/^$/!d;/^$/n;' ${TTMP}

cat <<BOF  > ${HTMP} 
<html><head><meta charset="UTF-8"/><style>body{font-size:2.8em;color:gold;background-color:black}pre{white-space: pre-wrap;word-wrap: break-word;}</style></head>
<body>
<pre>
BOF

#for one line long file format
if [ $(cat ${TTMP}|wc -l) == 0 ] && [ $(cat ${TTMP}|wc -c) -gt 5000 ]; then
    ST=1
    ED=666
    while :;
    do  
        text=$(cat ${TTMP}|cut -d' ' -f ${ST}-${ED}|jq -s -R -r @uri)
        tkk=$(python ${GOOGLE_TKK} ${text})
        curl ${PXY} -XPOST -d "client=gtx&dt=t&dj=1&ie=UTF-8&sl=auto&tl="${TO_LANG}"&q=${text}&tk=${tkk}" -s "${url}"|jq -r '.sentences[]|.trans'|tr -d '\n' >> ${HTMP} 
        ST=${ED}
        ED=$(($ST+666))
        if [ ${ED} -ge $(cat ${TTMP}|wc -w) ]; then
            ED=$(cat ${TTMP}|wc -w)
            text=$(cat ${TTMP}|cut -d' ' -f ${ST}-${ED}|jq -s -R -r @uri)
	    tkk=$(python ${GOOGLE_TKK} ${text})
	    curl ${PXY} -XPOST -d "client=gtx&dt=t&dj=1&ie=UTF-8&sl=auto&tl="${TO_LANG}"&q=${text}&tk=${tkk}" -s "${url}"|jq -r '.sentences[]|.trans'|tr -d '\n' >> ${HTMP} 
            break
        fi
        continue
    done

else
    ST=1
    ED=2
    _ED=0
    while :;
    do
        if [ $(sed -n "${ST},${ED}p" ${TTMP}|wc -c) -eq 0 ] && [ $ED -gt $(cat ${TTMP}|wc -l) ]; then
            break
        elif [ $(sed -n "${ST},${ED}p" ${TTMP}|wc -c) -le  5000 ] && [ $ED -gt $(cat ${TTMP}|wc -l) ]; then
            text=$(sed -n "${ST},${ED}p" ${TTMP}|jq -s -R -r @uri)
	    tkk=$(python ${GOOGLE_TKK} ${text})
	    curl ${PXY} -XPOST -d "client=gtx&dt=t&dj=1&ie=UTF-8&sl=auto&tl="${TO_LANG}"&q=${text}&tk=${tkk}" -s "${url}"|jq -r '.sentences[]|.trans' >> ${HTMP} 
            break
        elif [ $(sed -n "${ST},${ED}p" ${TTMP}|wc -c) -le  5000 ]; then
            ED=$(($ED+1))
            continue
        elif [ $(sed -n "${ST},${ED}p" ${TTMP}|wc -c) -gt 5000 ]; then
            _ED=$(($ED-1))
            while :;
            do
                line=$(sed -n "${_ED}p" ${TTMP})
                if [ -z "$line" ]; then
                    break
	        elif [[ $line =~ [!??!,,.。\"\”\’\']$ ]]; then
		    break
                else
                    _ED=$((${_ED}-1))
                    continue
                fi
            done
            text=$(sed -n "${ST},${_ED}p" ${TTMP}|jq -s -R -r @uri)
	    tkk=$(python ${GOOGLE_TKK} ${text})
	    curl ${PXY} -XPOST -d "client=gtx&dt=t&dj=1&ie=UTF-8&sl=auto&tl="${TO_LANG}"&q=${text}&tk=${tkk}" -s "${url}"|jq -r '.sentences[]|.trans' >> ${HTMP} 
            ST=$((${_ED}+1))
            ED=$(($ST+1))
            continue
        fi
    done
fi
cat <<BOF  >> ${HTMP} 
</pre>
</body></html>
BOF
#replace NULL string with new blank line
sed -i 's/\x0/\n\n/g' ${HTMP}
sed -i ':a;N;$!ba;s/\n\+/\n/g' ${HTMP}
surf -s -a a -i -d -t -g -n -x ${HTMP} 2>/dev/null &