#!/bin/bash

domain="$1"
schema_input="$2"
locationNumber="$3"

# Check if any of the variables are empty
if [[ -z "$domain" || -z "$schema_input" || -z "$locationNumber" ]]; then
    echo "Error: One or more required variables are empty. Please see the Tech Team."
    exit 2
fi

# Stores path to site within variable
websitePath=$(uapi --output=jsonpretty DomainInfo single_domain_data domain="$1" | jq -r '.result.data.documentroot')

if [ -z "$websitePath" ]; then
  echo "ERROR: Unable to retrieve website path. Please check with the Tech Team."
  exit 3
fi

cd "$websitePath" || exit 4

# Remove any surrounding quotes and unescape the JSON string
unescaped_schema=$(echo "$schema_input" | sed 's/^"//;s/"$//;s/\\"/"/g; s/&lt;/</g; s/&gt;/>/g; s/&quot;/"/g; s/&amp;/&/g')

#echo "DEBUG: $2"
#echo "DEBUG: $unescaped_schema"

# Check if unescaped_schema is empty
if [ -z "$unescaped_schema" ]; then
    echo "Schema is empty. Please make sure you've generated a schema first and try again."
    exit 2
fi

# Extract the number at the end of the string using sed
locationNumber=$(echo "$locationNumber" | sed -E 's/[^0-9]*([0-9]+)$/\1/')

#echo "DEBUG: $locationNumber"

# Add the script tags to the schema
schema_with_script_tags="<script type=\"application/ld+json\">$unescaped_schema</script>"

#define the variable to search for on the website
var_to_search="<script type='hcard-location$locationNumber'> </script>"

# Dry run for search and replace
dry_run_output="$(/usr/local/bin/php /usr/local/bin/wp search-replace "$var_to_search" 'PLACEHOLDER*' --dry-run --all-tables --report-changed-only --allow-root)"
if [ $? -ne 0 ]; then
    echo "WP-CLI search-replace command failed during dry run. Please check with the Tech Team."
    echo "$dry_run_output"
    exit 2
fi

if echo "$dry_run_output" | grep -q "0 replacements to be made."; then
    exit 1
else

    # Create a temporary file to hold the unescaped schema
    temp_schema_file=$(mktemp)
    echo "$schema_with_script_tags" > "$temp_schema_file"

    # Perform the actual search and replace using the contents of the temporary file
    search_output="$(/usr/local/bin/php /usr/local/bin/wp search-replace "$var_to_search" "$(cat "$temp_schema_file")" --all-tables --report-changed-only --allow-root)"
    if [ $? -ne 0 ]; then
        echo "WP-CLI search-replace command failed during replacement. Please check with the Tech Team."
        echo "$search_output"
        exit 2
    fi

    # Clean up the temporary file
    rm "$temp_schema_file"
fi

exit 0
