#!/bin/bash
CLOUDFLARE_ACCOUNT_ID=$1
CLOUDFLARE_API_TOKEN=$2
DOMAIN=$3
SCRIPT_NAME=$4


#CLOUDFLARE_ACCOUNT_ID="yqiang6@sina.com"
#CLOUDFLARE_API_TOKEN="Wsl2bNtp7LYXRJ-EvojrfbUT0CgbR15WWKDNvVHv"
#DOMAIN="yzqiang.dpdns.org"
#CRIPT_NAME="super-butterfly-8291"


ZONE_ID=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones?name=${DOMAIN}" \
  -H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \
  -H "Content-Type: application/json"| grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)

ROUTE_ID=`curl -s -X GET "https://api.cloudflare.com/client/v4/zones/${ZONE_ID}/workers/routes" \
  -H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \
  -H "Content-Type: application/json"|jq -r '.result[]|select(.script=="'${SCRIPT_NAME}'")'| \
jq -r '[.pattern,.id]| @csv'|sort |head -1|awk -F ',' '{print $2}'`
ROUTE_ID=${ROUTE_ID//\"/}

DATE=`date '+%Y%m%d%H'`

curl -s -X PUT \
  "https://api.cloudflare.com/client/v4/zones/${ZONE_ID}/workers/routes/${ROUTE_ID}" \
  -H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{"pattern": "'${DATE}'.'${DOMAIN}'/*","script": "'${SCRIPT_NAME}'"}'
  
#/www/set_cf_worker.sh yqiang6@sina.com   Wsl2bNtp7LYXRJ-EvojrfbUT0CgbR15WWKDNvVHv yzqiang.dpdns.org super-butterfly-8291
#/www/set_cf_worker.sh yqiang5@gmail.com  fe8PpTxWN9oYW5rYKFweuPrzwRSyNeAlm2dexulD smccb.dpdns.org wandering-leaf-a4d3
#/www/set_cf_worker.sh yqiang7@gmail.com  j7oP6kfuFHvMFElqIUfZRax5XMOttmYpk7du75-N yzqiang.qzz.io  odd-math-f8e0
#/www/set_cf_worker.sh yqiang9@gmail.com  g8fk6_bWfBI0eXQcLbXqIvDYM1kmStxB3Fw2qXop smccb.qzz.io  broken-shadow-fd4f 
