tag="webflow"

# get the current version of the package
current_version=$(jq -r '.version' package.json)

# get name of the package
package_name=$(jq -r '.name' package.json)

echo "Asigning the tag $tag to the current version of the package $package_name@$current_version"

# add "webflow" tag to the current version of the package
npm dist-tag add $package_name@$current_version $tag

echo "\nClearing the cache on CDN for the tag $tag"

# clear the cache on CDN for the tag "webflow"
request_id=$(curl -sX POST \
  https://purge.jsdelivr.net/ \
  -H 'content-type: application/json' \
  -d '{
        "path": [
          "/npm/'$package_name'@'$tag'/dist/sourcebuster.js",
          "/npm/'$package_name'@'$tag'/dist/sourcebuster.min.js"
        ]
      }' | jq -r '.id')

echo "\nRequest ID: $request_id"

# check the status of the request
status=$(curl -s https://purge.jsdelivr.net/status/$request_id | jq -r '.status')

# loop until the status is either "finished" or "failed"
while [ $status != "finished" ] && [ $status != "failed" ]
do
  status=$(curl -s https://purge.jsdelivr.net/status/$request_id | jq -r '.status')
  sleep 1
done

if [ $status == "failed" ]
then
  echo "\nFailed to clear the cache on CDN for $package_name with the tag $tag"
  echo "You can try to do it via the web interface of jsdelivr (https://www.jsdelivr.com/tools/purge)"
  exit 1
fi

paths=$(curl -s https://purge.jsdelivr.net/status/$request_id | jq -r '.paths')

echo "\nThrottled paths:"
echo $paths | jq -r 'to_entries[] | select(.value.throttled == true) | "\(.key) - throttling reset in \(.value.throttlingReset) seconds"'

are_throttled=$(echo $paths | jq -r 'to_entries[] | select(.value.throttled == true) | .key')

if [ -n "$are_throttled" ]
then
  echo "\nERROR: You should wait for the throttling reset time and try again to clear the cache"
  exit 1
fi

echo "\nSuccessfully cleared the cache on CDN for $package_name with the tag $tag"
