#!/bin/bash

if ! [ -f ~/.cloudflarerc ] ; then
  echo "No ~/.cloudflarerc file found. Cloudflare clear cache SKIPPED."
  exit 0
fi

. ~/.cloudflarerc
# this file contains only two lines in which we declare
# $apikey and $id
# like
# apikey=J9pq1v...
# id=16e255e...

echo -n "Clearing cloudflare cache..."

ret="$(curl -s -X DELETE "https://api.cloudflare.com/client/v4/zones/$id/purge_cache" \
     -H "Authorization: Bearer $apikey" \
     -H "Content-Type: application/json" \
     --data '{"purge_everything":true}')"

if [ -n "$(echo $ret | grep success)" ] ; then
  echo " Success!"
else
  echo " *** FAILED ***"
  echo "Could not clear cloudflare's cache. Update will not proceed."
  # exit with 1, so the update does not proceed, so we will know
  exit 1
fi