#!/bin/bash

_script_root=$(cd "$(dirname "$0")"; pwd)
_shname=`basename $0`
_date=`date +%F`

mkdir -p ${_script_root}/logs
_acclogfile="${_script_root}/logs/${_shname%.sh}_${_date}.log"
_errlogfile="${_script_root}/logs/${_shname%.sh}_${_date}.err"

key=$1
mess=$2

_codemessage=`curl "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=${key}" -H 'Content-Type: application/json' -d " { \"msgtype\": \"text\", \"text\": { \"content\": \"${mess}\" } }" 2>/dev/null `

_result=`echo "${_codemessage}" |grep errmsg |awk -F\" '{print $6}' |awk -F\. '{print $1}' `
if [ "${_result}k" == "okk" ];then
  echo "`date "+%F %T"` ok:${key}:${mess}" >>${_acclogfile}
else
  for i in `seq 1 2`
  do
    _codemessage=`curl "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=${key}" -H 'Content-Type: application/json' -d " { \"msgtype\": \"text\", \"text\": { \"content\": \"${mess}\" } }" 2>/dev/null `
    _result=`echo "${_codemessage}" |grep errmsg |awk -F\" '{print $6}' |awk -F\. '{print $1}' `
    if [ "${_result}k" == "okk" ];then
      echo "`date "+%F %T"` ok:${key}:${mess}" >>${_acclogfile}
      break
    else
      if [ "${i}k" == "5k" ];then
        echo "`date "+%F %T"` error:${key}:${mess}" >>${_errlogfile}
      else
        sleep 1
      fi
    fi
  done
fi

