#!/bin/bash

beginTime=`date +%s`

startTime=`date -d "24 hour ago" +"%Y%m%d%H%M%S"`
endTime=`date "+%Y%m%d%H%M%S"`
requestUrl=http://ci.openharmony.cn/api/ci-backend/ci-portal/v1/dailybuilds
requestBody='{"branch":"","buildFailReason":"","buildStatus":"success","component":"","deviceLevel":"","startTime":"'$startTime'","endTime":"'$endTime'","hardwareBoard":"","pageNum":1,"pageSize":99999,"projectName":"","testResult":""}'
data=$(curl -k -H "Content-Type: application/json" -X POST ${requestUrl} -d ${requestBody})
dailyBuildVos=$(echo $data | jq '.result.dailyBuildVos')
length=$(echo $dailyBuildVos | jq '. | length')
downloadPrefixUrl=http://download.ci.openharmony.cn
threadPoolSize=10
scanPath=/root/data/clamav/scanDir

[ -e /tmp/fd ] || mkfifo /tmp/fd1
exec 3<>/tmp/fd1
rm -rf /tmp/fd1
for ((i = 1; i <= $threadPoolSize; i++));
  do
    echo >&3
  done

freshclam
rm -rf $scanPath
mkdir -p $scanPath
 
for ((i = 0; i < $length; i++));
  do
    read -u3
    {
      obsPath=$(echo $dailyBuildVos | jq --argjson i $i '.[$i] | .obsPath' | sed 's/\"//g')
      projectName=$(echo $dailyBuildVos | jq --argjson i $i '.[$i] | .projectName' | sed 's/\"//g')
      branch=$(echo $dailyBuildVos | jq --argjson i $i '.[$i] | .branch' | sed 's/\"//g')
      component=$(echo $dailyBuildVos | jq --argjson i $i '.[$i] | .component' | sed 's/\"//g')
      buildStartTime=$(echo $dailyBuildVos | jq --argjson i $i '.[$i] | .buildStartTime' | sed 's/\"//g')
      fileName=$(echo $scanPath/$projectName#$branch#$component#$buildStartTime.tar.gz)
      directory=$(echo ${fileName%.tar.gz})
      echo "start dealing with:" $fileName .........
      wget $downloadPrefixUrl/$obsPath -O $fileName && mkdir -p $directory && tar zxvf $fileName -C $directory && clamscan -i -r $directory -l $directory.log && rm -f $fileName
      echo "scan $fileName finished ........."
      echo >&3
    }&
  done
wait  

finishTime=`date +%s`

echo "spending time: `expr $finishTime - $beginTime`"

exec 3<&-
exec 3>&-
