#!/bin/bash

domain=$1
firstPhoto=$2

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

cd $websitePath

if [[ -z "$firstPhoto" ]]; then
    echo "No Photos Selected."
    exit 1
fi

# If an existing zip file exists, remove it
if [ -e "media_export_files.zip" ]; then
    rm -f media_export_files.zip
fi

# Shift the arguments to skip the domain
shift 1

j=1

# Iterate over the remaining arguments in pairs
while (( "$#" )); do
    #define the variables
    media_name="$1"
    file_name="$2"
    alt_text="$3"
    
    file_path=$(echo "$file_name" | sed "s|https://www.$domain||")
    
    # Remove leading whitespace from file_path
    file_path="${file_path#" "}"

    #get base name of the file
    base_file_name=$(basename "$file_path")
    
    # Remove leading whitespace from alt_text
    alt_text="${alt_text#" "}"
    
    # Extract the file extension using awk
    file_extension=$(echo "$base_file_name" | awk -F . '{print $NF}')

    # Use the variables as needed
    echo "Media Name: $media_name"
    echo "File Path: $file_path"
    echo "File Name: $base_file_name"
    echo "Alt Text: $alt_text"
    echo
    
    # Destination directory
    destination_dir="media_export_file_$j"
    
    #echo "Current directory: $(pwd)"

    public_html="$(pwd)"
    # Remove trailing whitespace from the variable
    public_html="${public_html%% }"
    
    origin="$public_html$file_path"
    dest="$destination_dir/$base_file_name"
    
    # Create directory if it doesn't exist
    mkdir -p "$destination_dir"
    
    # Copy file to destination directory
    cp "$origin" "$dest"
    
    #ignore extra steps if file is already .webp
    if [[ "$dest" == *".webp"* ]]; then
        echo
    else
        # change file to webp
        cwebp -q 80 "$dest" -o "${dest%.$file_extension}.webp"
        
        #remove the copied file that IS NOT a .webp
        rm -f $dest
    fi
    
    # Add file info to a .txt file for importing
    echo "$media_name" >> $destination_dir/info.txt
    echo "${base_file_name%.$file_extension}.webp" >> $destination_dir/info.txt
    echo "$alt_text" >> $destination_dir/info.txt
    
    ((j++))
    
    # Move to the next argument
    shift 3

done

# Zip all media_export_file directories
zip -r media_export_files.zip media_export_file_*

# Remove media_export_file directories
rm -rf media_export_file_*