#!/bin/bash
# sh ./handler_leaks.sh /Users/cl/Downloads/zreport
# 检查是否提供了所有必需的参数
if [ "$#" -ne 1 ]; then
    echo "Usage: \$0 <outputPath>"
    exit 1
fi

outputPath=$1
echo "Attempting to read trace from ${outputPath}/trace.txt"
tracefile=$(cat ${outputPath}/trace.txt 2>/dev/null)
echo "Read trace: $tracefile"

leaksinfofile=${outputPath}/leaks_info


max_attempts=10
attempt=1
success=false

while [ $attempt -le $max_attempts ]; do
    echo "Attempt $attempt of $max_attempts"
    xcrun xctrace export --input $tracefile --xpath "//track[@name='Leaks']/details/detail[@name='Leaks']"  --output $leaksinfofile
    if [ $? -eq 0 ]; then
        echo "Command executed successfully on attempt $attempt"
        success=true
        break
    else
        echo "Command failed on attempt $attempt"
        ((attempt++))
    fi
    sleep 1
done


# 检查命令是否成功执行
if [ $? -ne 0 ]; then
    echo "xcrun xctrace export 命令执行失败"
    exit 1
fi


# 设置 webhook URL
url="https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=409ca504-2d5a-4a5c-a440-4762a1da7368"

# 设置消息内容
msg="leak in ${tracefile}"

# 构造 JSON 数据
data='{
  "msgtype": "text",
  "text": {
    "content": "'$msg'"
  }
}'

# 发送请求
send_request() {
  curl -X POST -H "Content-Type: application/json" -d "$data" "$url"
}



# 检查 leaks_info 文件中是否包含 "Agora" 字样
if grep -q "Agora" $leaksinfofile; then

#    重启wayang，默认Downloads下
    pkill -x WayangMacFFmpeg
    sleep 2
	  xcarchive_name=$(find $HOME/Downloads -name "*.xcarchive")
	  open ${xcarchive_name}/Products/Applications/WayangMacFFmpeg.app

    echo "发现 Agora 相关泄漏,重启Wayang"

    # 尝试发送请求,如果失败则等待后重试
    if ! send_request; then
      echo "Request failed"
      send_request
    fi
    pkill -f xctrace

    # 删除 leaks_info 文件
    rm $leaksinfofile
else
    echo "未发现 Agora 相关泄漏"
    # 删除 leaks_info 和 trace 文件
    rm $leaksinfofile
    rm -fr $tracefile
fi
#
#echo "处理完成"