#!/bin/bash

domain="$1"

# Ensure at least two arguments are passed
if [ "$#" -lt 2 ]; then
  echo "ERROR: Missing information!"
  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."
  exit 3
fi

cd "$websitePath"

# Shift the arguments to skip the domain
shift 1

# Iterate over the remaining arguments in pairs
while (( "$#" >= 1 ))
do
    combined_arg="$1" # The argument containing both URL and label

    # Split the combined argument into URL and label using the delimiter '|'
    IFS="|" read -ra arg_parts <<< "$combined_arg"
    fileUrl="${arg_parts[0]}"
    label="${arg_parts[1]}"
    
    echo "FileUrl = $fileUrl"
    echo "Label = $label"
    
    if [ -z "$fileUrl" ]; then
      echo "ERROR: Can't find File URL!"
      exit 6
    fi

    if [ -z "$label" ]; then
      echo "ERROR: No Title on Image!"
      exit 7
    fi

    #define variables to download from chiro images site
    fromIP="18.214.60.67"
    fromDomain=chiro.inceptionimages.com
    fromDomainFull="$fileUrl"
    fromDomainFull="$(echo -e "${fromDomainFull}" | tr -d '[:space:]')"
    fileName=$(basename $fromDomainFull)
    
    echo $fileName
    echo $label
    
    #download the image
    wget "$fromDomainFull" -O "$fileName"

    # import the image
    import=$(/usr/local/bin/php /usr/local/bin/wp media import "$fileName" --title="OPTIMIZATION* $label in CITY* STATE*" --alt="OPTIMIZATION* $label in CITY* STATE*")
    
    rm -f $fileName

    # Shift the processed arguments
    shift 1
done

exit 0