HEX
Server: nginx/1.29.3
System: Linux 11979.bigscoots-wpo.com 6.8.0-88-generic #89-Ubuntu SMP PREEMPT_DYNAMIC Sat Oct 11 01:02:46 UTC 2025 x86_64
User: nginx (1068)
PHP: 7.4.33
Disabled: exec,system,passthru,shell_exec,proc_open,proc_close,popen,show_source,cmd# Do not modify this line # 1684243876
Upload Files
File: //bigscoots/wpo/cloudflare/bscache.sh
#!/bin/bash

source /bigscoots/includes/common.sh
source /bigscoots/wpo/extras/bigscoots.menu

CFAPIURL=https://api.cloudflare.com/client/v4

encrypt_it() {
  local salt="$1"
  echo -n "$salt" | openssl enc -aes-256-cbc -base64 -A -K "546573746b6579" -iv "c25e89f34f9878266bede60ed2feddde" 2>/dev/null
}

# Function to display help
function show_help {
  echo "Usage: $0 {install|remove|remove_cfe|status|add_cf_rule} --domain DOMAIN [--cfuser email] [--cfapikey apikey|--cftoken token] [--cfzoneid zoneid]"
  echo ""
  echo "Commands:"
  echo "install    Install BigScoots Cache and add cache rules. You must provide --domain. Optionally add --cfuser, --cfapikey, --cftoken, --cfzoneid"
  echo "          Example: $0 install --domain example.com --cfuser \"cfuser\" --cfapikey \"cfapikey123\"  --cfzoneid \"pcfzoneid123\""
  echo "          Example with API Token: $0 install --domain example.com --cftoken \"cfapitoken123\" --cfzoneid \"pcfzoneid123\""
  echo ""
  echo "remove    Remove BigScoots Cache and cache rules. You must provide --domain."
  echo "          Example: $0 remove --domain example.com"
  echo ""
  echo "remove_cfe    Remove BigScoots Cloudflare Enterprise. You must provide --domain."
  echo "          Example: $0 remove --domain example.com"
  echo ""
  echo "status    Check the status of BigScoots Cache. You must provide --domain."
  echo "          Example: $0 status --domain example.com"
  echo ""
  echo "add_cf_rule    Add only the BigScoots Cloudflare cache rule without touching the plugin."
  echo "          Example: $0 add_cf_rule --domain example.com --cfuser \"cfuser\" --cfapikey \"cfapikey123\" --cfzoneid \"pcfzoneid123\""
  echo ""
}

get_canonical() {
    local status=true
    local err_output=""
    
    # First attempt: get canonical using wpcli option get home and suppress warnings
    if ! canonical=$(wpcli option get home --path=${DOCROOT} 2>/dev/null | sed -e 's|^[^/]*//||' -e 's|/.*$||'); then
        # If the first attempt fails, try wpcli eval home_url and capture any errors
        if ! err_output=$(wpcli eval 'echo home_url();' --path=${DOCROOT} 2>&1 >/dev/null); then
            # If the second attempt also fails, set status to false
            status=false
        else
            # If the second attempt succeeds, capture the actual output without warnings
            canonical=$(wpcli eval 'echo home_url();' --path=${DOCROOT} 2>/dev/null)
        fi
    fi
    
    # Handle failures and send Slack alerts if status is false
    if [ "$status" = false ]; then
        # Send error message to Slack including error details
        send_slack_alert "#wpo-alerts" ":warning:" "Unable to get Canonical URL - Function: \`get_canonical\`" "$domain" "$err_output"
        echo "{\"status\":\"fail\",\"msg\":\"An issue occurred while activating the cache. Support has been alerted!\"}"
        exit 1
    fi
}


remove_swcfpc_constants() {
    local err_output=""

    swcfpc_constants=("SWCFPC_CF_API_EMAIL" "SWCFPC_CF_API_KEY" "SWCFPC_CF_API_ZONE_ID")

    for swcfpc_constant in "${swcfpc_constants[@]}"; do
        if wpcli config has "$swcfpc_constant" --path="${DOCROOT}" 2>/dev/null; then
            if ! err_output=$(wpcli config delete "$swcfpc_constant" --path="${DOCROOT}" 2>&1); then
                send_slack_alert "#wpo-alerts" ":warning:" "Removing SWCFPC Constants - Function: \`remove_swcfpc_constants\`" "$domain" "Failed removing $swcfpc_constant\n$err_output"
            fi
        fi
    done
}

get_zone_id() {
  if [[ -n "$cfapikey" ]]; then
    # Use API Key Authentication
    zone_id=$(curl -s -X GET "${CFAPIURL}/zones?name=$domain" \
      -H "X-Auth-Email: $cfuser" \
      -H "X-Auth-Key: $cfapikey" \
      -H "Content-Type: application/json" | jq -r '.result[0].id')
  
  elif [[ -n "$cftoken" ]]; then
    # Use API Token Authentication
    zone_id=$(curl -s -X GET "${CFAPIURL}/zones?name=$domain" \
      -H "Authorization: Bearer $cftoken" \
      -H "Content-Type: application/json" | jq -r '.result[0].id')

  else
    echo "Error: No Cloudflare authentication method provided."
    return 1
  fi

  # Return the zone ID if found, otherwise return an error
  if [[ -z "$zone_id" || "$zone_id" == "null" ]]; then
    echo "Error: Failed to retrieve Cloudflare Zone ID for $domain."
    return 1
  else
    echo "$zone_id"
  fi
}

cf_cred_check() {
  missing_creds=()

  # Check if either cfapikey or cftoken is set (one must be provided)
  if [[ -z "$cfapikey" && -z "$cftoken" ]]; then
    missing_creds+=("--cfapikey or --cftoken (one is required)")
  fi

  # If cfapikey is provided, cfuser is also required
  if [[ -n "$cfapikey" && -z "$cfuser" ]]; then
    missing_creds+=("--cfuser (required when using --cfapikey)")
  fi

  # If any credentials are missing, send alert and exit
  if [[ ${#missing_creds[@]} -gt 0 ]]; then
    missing_list=$(IFS=", "; echo "${missing_creds[*]}")

    # Send Slack alert
    send_slack_alert "#wpo-alerts" ":warning:" \
      "Missing Cloudflare Credentials - Function: \`cf_cred_check\`" "$domain" \
      "The following required credentials are missing: $missing_list"

    # JSON response
    echo "{\"status\":\"fail\",\"msg\":\"Missing Cloudflare API credentials ($missing_list) for $domain, unable to proceed. Support has been alerted!\"}"
    
    exit 1
  fi

  # If cfzoneid is not provided, try to retrieve it
  if [[ -z "$cfzoneid" ]]; then
    cfzoneid=$(get_zone_id)
    
    # If retrieval fails, exit
    if [[ -z "$cfzoneid" || "$cfzoneid" == "null" ]]; then
      send_slack_alert "#wpo-alerts" ":warning:" \
        "Failed to Retrieve Zone ID - Function: \`cf_cred_check\`" "$domain" \
        "Attempted to fetch Cloudflare Zone ID but failed."

      echo "{\"status\":\"fail\",\"msg\":\"Unable to retrieve Cloudflare Zone ID for $domain, exiting.\"}"
      exit 1
    fi
  fi
}


bs_cache_configure_cfapikey_creds() {
    local cfuser="$1"
    local cfapikey="$2"
    local cfzoneid="$3"
    local err_output=""

    # Check if all parameters are provided
    if [[ -z "$cfuser" || -z "$cfapikey" || -z "$cfzoneid" ]]; then
        echo "{\"status\":\"fail\",\"msg\":\"Missing Cloudflare API credentials for $domain, unable to proceed. Support has been alerted!\"}"
        return 1  # Use return instead of exit
    fi

    # Encrypt values
    local encrypted_cfuser=$(encrypt_it "$cfuser")
    local encrypted_cfapikey=$(encrypt_it "$cfapikey")
    local encrypted_cfzoneid=$(encrypt_it "$cfzoneid")

    # Skip unnecessary plugins
    SKIPPLUGINS=$(skip_all_plugins_except bigscoots-cache)

    # Run wp command and capture errors correctly
    if ! err_output=$(wp bs_cache set_connection_details \
        --path="${DOCROOT}" \
        --cf-email-salt="$encrypted_cfuser" \
        --cf-api-key-salt="$encrypted_cfapikey" \
        --cf-zone-id-salt="$encrypted_cfzoneid" \
        --allow-root --skip-themes --skip-plugins="${SKIPPLUGINS}" \
        --require=/bigscoots/includes/err_report.php >/dev/null 2>&1); then
        err_output+=" set_connection_details"
        send_slack_alert "#wpo-alerts" ":warning:" "Installing BigScoots Cache - Function: \`bs_cache_configure_cfapikey_creds\`" "$domain" "$err_output"
        return 1  # Return failure status
    fi
}

bs_cache_configure_cfapitoken_creds() {
    local cfapitoken="$1"
    local cfzoneid="$2"
    local err_output=""

    # Check if all parameters are provided
    if [[ -z "$cfapitoken" ]] || [[ -z "$cfzoneid" ]]
    then
        echo "{\"status\":\"fail\",\"msg\":\"Missing Cloudflare API Token for $domain, unable to proceed.  Support has been alerted!\"}"
        exit 1
    fi

    # Encrypt and set as constant
    local encrypted_cfapitoken=$(encrypt_it "$cfapitoken")
    local encrypted_cfzoneid=$(encrypt_it "$cfzoneid")

    # Skip unnecessary plugins
    SKIPPLUGINS=$(skip_all_plugins_except bigscoots-cache)

    # Run wp command and capture errors correctly
    if ! err_output=$(wp bs_cache set_connection_details \
        --path="${DOCROOT}" \
        --cf-api-token-salt="$encrypted_cfapitoken" \
        --cf-zone-id-salt="$encrypted_cfzoneid" \
        --allow-root --skip-themes --skip-plugins="${SKIPPLUGINS}" \
        --require=/bigscoots/includes/err_report.php >/dev/null 2>&1); then
        err_output+=" set_connection_details"
        send_slack_alert "#wpo-alerts" ":warning:" "Installing BigScoots Cache - Function: \`bs_cache_configure_cfapitoken_creds\`" "$domain" "$err_output"
        return 1  # Return failure status
    fi
}

domain_exist_check() {
		if [ ! -d "$DOCROOT" ]
		then
				echo "{\"status\":\"fail\",\"msg\":\"An issue occured while activating the cache.  Support has been alerted!\"}"
				send_slack_alert "#wpo-alerts" ":warning:" "Installing BigScoots Cache - Function: \`domain_exist_check\`" "$domain" "$DOCROOT doesnt exist."
	      exit 1
	  elif [ ! -f "$DOCROOT/wp-config.php" ]
		then
				echo "{\"status\":\"fail\",\"msg\":\"An issue occured while activating the cache.  Support has been alerted!\"}"
				send_slack_alert "#wpo-alerts" ":warning:" "Installing BigScoots Cache - Function: \`domain_exist_check\`" "$domain" "$DOCROOT/wp-config.php doesnt exist."
	      exit 1
	  fi
}

install_bs_cache() {
		local status=true
		local err_output

        SKIPPLUGINS=$(skip_all_plugins_except bigscoots-cache)

		err_output=$(wpcli plugin install https://wp-plugins.bigscoots.com/download/bigscoots-cache --path=${DOCROOT} --force --activate 2>&1 >/dev/null) || status=false
		err_output+=$(wp bs_cache enable_cache --path=${DOCROOT} --allow-root --skip-themes --skip-plugins="${SKIPPLUGINS}" --require=/bigscoots/includes/err_report.php 2>&1 >/dev/null || status=false)

		if [ "$status" = false ]
		then
			send_slack_alert "#wpo-alerts" ":warning:" "Installing BigScoots Cache - Function: \`install_bs_cache\`" "$domain" "$err_output"
		fi
}

uninstall_swcfpc() {
    local err_output
    local status=true

    SKIPPLUGINS=$(skip_all_plugins_except bigscoots-cache)

    if wpcli plugin is-installed wp-cloudflare-page-cache --path=${DOCROOT}
    then
        remove_cf_rules
        err_output=$(wp plugin uninstall wp-cloudflare-page-cache --deactivate --allow-root --skip-themes --skip-plugins="${SKIPPLUGINS}" --path="${DOCROOT}" 2>&1 >/dev/null) || status=false
    fi

    if [ "$status" = false ]
    then
        send_slack_alert "#wpo-alerts" ":warning:" "Uninstalling Super Page Cache Plugin - Function: \`uninstall_swcfpc\`" "$domain" "$err_output"
    fi
}

uninstall_bs_cache() {
    local err_output
    local status=true

    SKIPPLUGINS=$(skip_all_plugins_except bigscoots-cache)

    if wpcli plugin is-installed bigscoots-cache --path=${DOCROOT} 2>/dev/null
    then
        err_output=$(wp plugin uninstall bigscoots-cache --deactivate --allow-root --skip-themes --skip-plugins="${SKIPPLUGINS}" --path="${DOCROOT}" 2>&1 >/dev/null) || status=false
    fi

    [ -f "$DOCROOT"/wp-content/mu-plugins/wp-rocket-no-cache.php ] && rm -f "$DOCROOT"/wp-content/mu-plugins/wp-rocket-no-cache.php
    [ -d "$DOCROOT"/wp-content/bigscoots-cache ] && rm -rf "$DOCROOT"/wp-content/bigscoots-cache

    if [ "$status" = false ]
    then
        send_slack_alert "#wpo-alerts" ":warning:" "Uninstalling BigScoots Cache plugin - Function: \`uninstall_bs_cache\`" "$domain" "$err_output"
    fi
}

remove_cf_constants() {
    local status=true
    local err_output=""

    # Check if variables are set and perform operations
    if wpcli config get BS_SITE_CF_EMAIL_SALT --path=${DOCROOT} >/dev/null 2>&1
    then
        err_output=$(wpcli config delete BS_SITE_CF_EMAIL_SALT --path=${DOCROOT} 2>&1 >/dev/null) || status=false
    fi

    if wpcli config get BS_SITE_CF_API_KEY_SALT --path=${DOCROOT} >/dev/null 2>&1
    then
        err_output=$(wpcli config delete BS_SITE_CF_API_KEY_SALT --path=${DOCROOT} 2>&1 >/dev/null) || status=false
    fi

    if wpcli config get BS_SITE_CF_ZONE_ID_SALT --path=${DOCROOT} >/dev/null 2>&1
    then
        err_output=$(wpcli config delete BS_SITE_CF_ZONE_ID_SALT --path=${DOCROOT} 2>&1 >/dev/null) || status=false
    fi

    if [ "$status" = false ]
    then
        send_slack_alert "#wpo-alerts" ":warning:" "Remving BigScoots Cache - Function: \`remove_cf_constants\`" "$domain" "$err_output"
    fi
}

remove_cfe_constants() {
    local status=true
    local err_output=""

    # Check if variables are set and perform operations
    if wpcli config get BigScoots_CFE --path=${DOCROOT} >/dev/null 2>&1
    then
        err_output=$(wpcli config delete BigScoots_CFE --path=${DOCROOT} 2>&1 >/dev/null) || status=false
    fi

    if wpcli config get BIGSCOOTS_CFE --path=${DOCROOT} >/dev/null 2>&1
    then
        err_output=$(wpcli config delete BIGSCOOTS_CFE --path=${DOCROOT} 2>&1 >/dev/null) || status=false
    fi

    if grep -q '.bigscoots/cf/pkey' "${DOCROOT}/wp-config.php"
    then
        sed -i '/.bigscoots\/cf\/pkey_[0-9]*.php/d' "${DOCROOT}/wp-config.php"
    fi

    if [ -n "$pkey" ]
    then
        [ -f /home/nginx/.bigscoots/cf/pkey_"$pkey".php ] && rm -f /home/nginx/.bigscoots/cf/pkey_"$pkey".php
    fi

    if [ "$status" = false ]
    then
        send_slack_alert "#wpo-alerts" ":warning:" "Converting Free Cloudflare to BigScoots Cache - Function: \`remove_cfe_constants\`" "$domain" "$err_output"
    fi
}

remove_cf_rules() {
  err_output=$(curl --location 'https://main.bigscoots.com/remove-spcfc-cf-rules/' \
  --header 'Content-Type: application/json' \
  --header 'x-bigscoots-user: webmaster' \
  --data '{
    "action": "spcfc_cf_rules_cleanup",
    "hostname": "'"$canonical"'",
    "cf_email": "'"$cfuser"'",
    "cf_global_api_key": "'"$cfapikey"'",
    "cf_zone_id": "'"$cfzoneid"'"
  }' 2>&1) || send_slack_alert "#wpo-alerts" ":warning:" "Failed to remove specific Cloudflare rules - Function: \`remove_cf_rules\`" "$domain" "$err_output"
}

wprocket_changes() {
  if [ -d "$DOCROOT/wp-content/plugins/wp-rocket" ]; then
    if wpcli plugin is-active wp-rocket --path="$DOCROOT" >/dev/null 2>&1; then
      wpcli config set WP_CACHE false --path="$DOCROOT" >/dev/null 2>&1
      echo -n > "$DOCROOT/wp-content/advanced-cache.php"
      [ -d "$DOCROOT/wp-content/cache/wp-rocket" ] && rm -rf "$DOCROOT/wp-content/cache/wp-rocket" >/dev/null 2>&1

      # Ensure bigscoots-helper is installed and active
      if [ -d "$DOCROOT/wp-content/plugins/bigscoots-helper" ]; then
        if ! wpcli plugin is-active bigscoots-helper --path="$DOCROOT" >/dev/null 2>&1; then
          wpcli plugin activate bigscoots-helper --path="$DOCROOT" >/dev/null 2>&1
        fi
      else
        wpcli plugin install https://wp-plugins.bigscoots.com/download/bigscoots-helper --path="$DOCROOT" --activate >/dev/null 2>&1
      fi

      # Get plugin skip list
      skip_plugins=$(skip_all_plugins_except bigscoots-helper)

      # Check WP Rocket Manager module status
      wp_rocket_manager_module_check=$(wp bs_helper list_modules --format=json --path="$DOCROOT" --skip-plugins="$skip_plugins" --skip-themes --allow-root 2>/dev/null | jq -r '.[] | select(.id=="wp-rocket-manager") | .status')

      # Check if WP Rocket page cache is disabled
      wp_rocket_disable_page_cache=$(wp bs_helper get_general_settings --format=json --path="$DOCROOT" --skip-plugins="$skip_plugins" --skip-themes --allow-root 2>/dev/null | jq -r '.[] | select(.name=="wp_rocket_disable_page_cache") | .value')

      # Enable WP Rocket Manager module if it's disabled
      if [ "$wp_rocket_manager_module_check" == "Disabled" ]; then
        wp bs_helper enable_module wp-rocket-manager --path="$DOCROOT" --skip-plugins="$skip_plugins" --skip-themes --allow-root >/dev/null 2>&1
      fi

      # Disable WP Rocket page cache if not already disabled
      if [ "$wp_rocket_disable_page_cache" == "off" ]; then
        wp bs_helper set_general_settings --wp-rocket-disable-page-caching=on --path="$DOCROOT" --skip-plugins="$skip_plugins" --skip-themes --allow-root >/dev/null 2>&1
      fi
    fi

  # Remove wp-rocket-no-cache.php if it exists and WP Rocket is not installed
  elif [ -f "$DOCROOT/wp-content/mu-plugins/wp-rocket-no-cache.php" ]; then
    rm -f "$DOCROOT/wp-content/mu-plugins/wp-rocket-no-cache.php"
  fi
}

bigscoots_cache_status() {
    SKIPPLUGINS=$(skip_all_plugins_except bigscoots-cache)
    
    if wpcli plugin is-installed bigscoots-cache --path=${DOCROOT} 2>/dev/null
    then
        if wpcli plugin is-active bigscoots-cache --path=${DOCROOT} 2>/dev/null
        then
            # Plugin is installed and active
            plugin_status=$(wp bs_cache status --allow-root --skip-themes --skip-plugins="${SKIPPLUGINS}" --require=/bigscoots/includes/err_report.php --format=json --path=${DOCROOT} 2>/dev/null)
            echo "{\"status\":\"success\",\"message\":\"Plugin bigscoots-cache is installed and active.\",\"plugin\":\"bigscoots-cache\",\"active\":true,\"plugin_status\":$plugin_status,\"action\":\"Check Mark\"}" | jq
        else
            # Plugin is installed but not active
            echo "{\"status\":\"error\",\"message\":\"Plugin bigscoots-cache is installed but not active.\",\"plugin\":\"bigscoots-cache\",\"active\":false,\"action\":\"Exclamation Point - Give the customer the option to activate the plugin in the website's admin panel.\"}" | jq
        fi
    else
        # Plugin is not installed
        echo "{\"status\":\"error\",\"message\":\"Plugin bigscoots-cache is not installed.\",\"plugin\":\"bigscoots-cache\",\"active\":false,\"action\":\"Red X - Give Customer option to install the bigscoots-cache.\"}" | jq
    fi
}

enable_standard_plan() {
  local api_url="https://main.bigscoots.com/bscache-usage-log/api/"
  local content_type="Content-Type: application/json"
  local security_header="x-bigscoots-user: webmaster"
  local server_ip="$serverip"
  local hostname="$canonical"
  local server_hostname="$(hostname)"
  local data='{
    "action": "enable_plan",
    "hostname": "'"$hostname"'",
    "server_ip": "'"$server_ip"'",
    "server_hostname": "'"$server_hostname"'",
    "plan": "standard"
  }'

  local response=$(curl -s --header "$content_type" --header "$security_header" --data "$data" "$api_url")

  if [[ $response == *"\"success\": false"* ]]
  then
    send_slack_alert "#wpo-alerts" ":warning:" "Function: \`enable_standard_plan\`" "$hostname" "$response"
  fi
}

disable_standard_plan() {
  local api_url="https://main.bigscoots.com/bscache-usage-log/api/"
  local content_type="Content-Type: application/json"
  local security_header="x-bigscoots-user: webmaster"
  local hostname="$canonical"
  local data='{
    "action": "remove_plan",
    "hostname": "'"$hostname"'",
    "plan": "standard"
  }'

  local response=$(curl -s --header "$content_type" --header "$security_header" --data "$data" "$api_url")

  if [[ $response == *"\"success\": false"* ]]
  then
    send_slack_alert "#wpo-alerts" ":warning:" "Function: \`disable_standard_plan\`" "$hostname" "$response"
  fi
}

disable_performance_plan() {
  local api_url="https://main.bigscoots.com/bscache-usage-log/api/"
  local content_type="Content-Type: application/json"
  local security_header="x-bigscoots-user: webmaster"
  local server_ip="$serverip"
  local hostname="$CFAPI_CANONICALDOMAIN"
  local server_hostname="$(hostname)"
  local data='{
    "action": "remove_plan",
    "hostname": "'"$hostname"'",
    "plan": "performance+"
  }'

    local response=$(curl -s --header "$content_type" --header "$security_header" --data "$data" "$api_url")

  if [[ $response == *"\"success\": false"* ]]
  then
    send_slack_alert "#wpo-alerts" ":warning:" "Function: \`disable_performance_plan\`" "$hostname" "$response"
  fi
}

toggle_pagecaching() {
  # Get plugin skip list
  local skip_plugins=$(skip_all_plugins_except bigscoots-cache)

  if [[ -n $pagecache ]]; then
    if [[ $pagecache == "disable" ]]; then
      if wp bs_cache page_cache disable --path="$DOCROOT" --skip-plugins="$skip_plugins" --skip-themes --allow-root >/dev/null 2>&1; then
        echo "{\"status\":\"success\",\"msg\":\"BigScoots enterprise page caching has been disabled!\"}"
      else
        echo "{\"status\":\"false\",\"msg\":\"Failed to disable page caching, support has been alerted.\"}"
        send_slack_alert "#wpo-alerts" ":warning:" "Function: \`toggle_pagecaching\`" "$hostname" "WP-CLI disable failed. DOCROOT=$DOCROOT"
        return 1
      fi
    elif [[ $pagecache == "enable" ]]; then
      if wp bs_cache page_cache enable --path="$DOCROOT" --skip-plugins="$skip_plugins" --skip-themes --allow-root >/dev/null 2>&1; then
        echo "{\"status\":\"success\",\"msg\":\"BigScoots enterprise page caching has been enabled!\"}"
      else
        echo "{\"status\":\"false\",\"msg\":\"Failed to enable page caching, support has been alerted.\"}"
        send_slack_alert "#wpo-alerts" ":warning:" "Function: \`toggle_pagecaching\`" "$hostname" "WP-CLI enable failed. DOCROOT=$DOCROOT"
        return 1
      fi
    elif [[ $pagecache == "status" ]]; then
      # Check BigScoots Cache Status - Plugin Cache Status
      local bs_cache_status=$(wp bs_cache status --format=json --path="$DOCROOT" --skip-plugins="$skip_plugins" --skip-themes --allow-root 2>/dev/null | jq -r '.[]? | select(.name=="Plugin Cache Status") | .value')

      if [[ -z $bs_cache_status ]]; then
        echo "{\"status\":\"false\",\"msg\":\"Status check failed (unexpected output). Support has been alerted.\"}"
        send_slack_alert "#wpo-alerts" ":warning:" "Function: \`toggle_pagecaching\`" "$hostname" "Could not parse Plugin Cache Status from wp bs_cache status."
        return 1
      fi

      if [[ "$bs_cache_status" == "Page Cache Disabled" ]]; then
        echo "{\"status\":\"success\",\"msg\":\"disabled\"}"
      else
        echo "{\"status\":\"success\",\"msg\":\"enabled\"}"
      fi
      else
        echo "{\"status\":\"false\",\"msg\":\"Issue detected while attempting to update page caching, support has been alerted.\"}"
        send_slack_alert "#wpo-alerts" ":warning:" "Function: \`toggle_pagecaching\`" "$hostname" "\$pagecache was not set properly, its defined as: $pagecache"
        return 1
      fi
  else
    echo "{\"status\":\"false\",\"msg\":\"Issue detected while attempting to update page caching, support has been alerted.\"}"
    send_slack_alert "#wpo-alerts" ":warning:" "Function: \`toggle_pagecaching\`" "$hostname" "\$pagecache was not set, empty."
    return 1
  fi
}

add_bigscoots_cache_rule_to_cf() {
    local err_output=""
    local response=""

    response=$(curl -s --location 'https://n8n.bigscoots.dev/webhook/cf/bigscoots-cache' \
        --header 'Authorization: Bearer bd602ba6-4106-47d8-9dcb-3fbd87eb68a8' \
        --header 'Content-Type: application/json' \
        --data '{
            "action": "add",
            "domain": "'"$domain"'",
            "cf_email": "'"$cfuser"'",
            "cf_api_key": "'"$cfapikey"'",
            "cf_zone_id": "'"$cfzoneid"'"
        }') || err_output="Curl failed"

    if [[ $response == *"\"success\": false"* || -n "$err_output" ]]; then
        send_slack_alert "#wpo-alerts" ":warning:" \
            "Function: \`add_bigscoots_cache_rule_to_cf\`" "$domain" \
            "${response:-$err_output}"
    fi
}

remove_bigscoots_cache_rule_to_cf() {
    local err_output=""
    local response=""

    response=$(curl -s --location 'https://n8n.bigscoots.dev/webhook/cf/bigscoots-cache' \
        --header 'Authorization: Bearer bd602ba6-4106-47d8-9dcb-3fbd87eb68a8' \
        --header 'Content-Type: application/json' \
        --data '{
            "action": "remove",
            "domain": "'"$domain"'",
            "cf_email": "'"$cfuser"'",
            "cf_api_key": "'"$cfapikey"'",
            "cf_zone_id": "'"$cfzoneid"'"
        }') || err_output="Curl failed"

    if [[ $response == *"\"success\": false"* || -n "$err_output" ]]; then
        send_slack_alert "#wpo-alerts" ":warning:" \
            "Function: \`remove_bigscoots_cache_rule_to_cf\`" "$domain" \
            "${response:-$err_output}"
    fi
}

# Check command line arguments
if [[ $# -lt 2 ]]
then
  show_help
  exit 1
fi

# Parse command line arguments
command=$1
shift
while (( "$#" ))
do
  case "$1" in
    --domain)
      domain=$2
      shift 2
      ;;
    --cfuser)
      cfuser=$2
      shift 2
      ;;
    --cfapikey)
      cfapikey=$2
      shift 2
      ;;
    --cftoken)
      cftoken=$2
      shift 2
      ;;
    --cfzoneid)
      cfzoneid=$2
      shift 2
      ;;
    --pkey)
      pkey=$2
      shift 2
      ;;
    --page-cache)
      pagecache=$2
      shift 2
      ;;
    *)
      echo "Invalid command"
      show_help
      exit 1
      ;;
  esac
done

DOCROOT="/home/nginx/domains/$domain/public"

case $command in
  install)
    validate_domain "${domain}"
    domain_exist_check
    get_canonical
    cf_cred_check
    install_bs_cache
    remove_swcfpc_constants
    uninstall_swcfpc
    if [ -n "$cfapikey" ]; then
        bs_cache_configure_cfapikey_creds "$cfuser" "$cfapikey" "$cfzoneid"
    elif [ -n "$cftoken" ]; then
        bs_cache_configure_cfapitoken_creds "$cftoken" "$cfzoneid"
    fi
    wprocket_changes
    enable_standard_plan
    add_bigscoots_cache_rule_to_cf
    scoots php reload all > /dev/null 2>&1
    bash -c "source /bigscoots/includes/common.sh ; correct_permissions_ownership '${domain}' > /dev/null 2>&1 & disown"
    echo "{\"status\":\"success\",\"canonical\":\"$canonical\",\"msg\":\"BigScoots caching has been activated!\"}"
    #send_slack_alert "#dev-plugin" ":cloudflare:" "BigScoots Cache: \`Installed\` :rocket:" "$domain" "Using the new method, please check."
    exit 0
    ;;
  remove)
    validate_domain "${domain}"
    domain_exist_check
    get_canonical
    uninstall_bs_cache
    remove_cf_constants
    disable_standard_plan
    remove_bigscoots_cache_rule_to_cf
    scoots php reload all > /dev/null 2>&1
    bash -c "source /bigscoots/includes/common.sh ; correct_permissions_ownership '${domain}' > /dev/null 2>&1 & disown"
    echo "{\"status\":\"success\",\"msg\":\"BigScoots caching has been deactivated!\"}"
    #send_slack_alert "#dev-plugin" ":cloudflare:" "BigScoots Cache: \`Uninstalled\` :cry:" "$domain" "N/A"
    exit 0
    ;;
  remove_cfe)
    validate_domain "${domain}"
    domain_exist_check
    get_canonical
    uninstall_bs_cache
    remove_cfe_constants
    disable_performance_plan
    scoots php reload all > /dev/null 2>&1
    bash -c "source /bigscoots/includes/common.sh ; correct_permissions_ownership '${domain}' > /dev/null 2>&1 & disown"
    echo "{\"status\":\"success\",\"msg\":\"BigScoots enterprise caching has been deactivated!\"}"
    #send_slack_alert "#dev-plugin" ":cloudflare:" "BigScoots Cache: \`Uninstalled\` :cry:" "$domain" "N/A"
    exit 0
    ;;
  pagecache_cfe)
    validate_domain "${domain}"
    domain_exist_check
    toggle_pagecaching "${pagecache}"
    scoots php reload all > /dev/null 2>&1
    exit 0
    ;;
  add_cf_rule)
    cf_cred_check
    # At this point cfzoneid is guaranteed to be set (or we already exited).
    add_bigscoots_cache_rule_to_cf
    echo "{\"status\":\"success\",\"msg\":\"BigScoots Cloudflare cache rule has been added/updated for $domain.\"}"
    exit 0
    ;;
  status)
    bigscoots_cache_status "$domain"
    ;;
  *)
    echo "Invalid command"
    show_help
    exit 1
    ;;
esac