#bin/bash

echo "$1"
echo "$2"
echo "$3"
echo "$4"


# Validate arguments
if [ "$#" -lt 2 ]; then
  echo "ERROR: Image Must Be Selected!"
  exit 1
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"

# Temporary directory to store the downloaded images before zipping
temp_directory="$websitePath/temp_image_directory/"

# Create the temporary directory if it doesn't exist
mkdir -p "$temp_directory"

# 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]}"

    # Remove leading and trailing spaces from the label
    label=$(echo "$label" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
    
    # Replace spaces in the label with underscores (or any other desired character)
    label_with_underscores="${label// /_}"

    # Construct the destination path for the image
    destination_path="$temp_directory/${label_with_underscores}.png"

    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

    # Use curl to download the image
    curl -o "$destination_path" "$fileUrl"

    # Check if the download was successful
    if [ $? -eq 0 ]; then
        # Shift the processed arguments
        shift 1
    else
        echo "Failed to download the image."
        exit 1
    fi
    
done

# Create a ZIP file containing the downloaded images
cd "$temp_directory"
zip_file="${temp_directory}downloaded_images.zip"
zip -r "$zip_file" ./*

# Move the zip file to its final destination
mv "$zip_file" "$websitePath/downloaded_images.zip"
cd "$websitePath"

# Clean up by removing temporary downloaded images
rm -rf "$temp_directory"

exit 0