#!/bin/zsh

# MAC MINI
# THIS IS RUNNING DIRECTLY IN HAZEL. ANY CHANGES HERE SHOULD BE CHANGED THERE TOO.

# Define constants for the local folder path, S3 bucket name, and backup folder path
LOCAL_FOLDER_PATH="/Users/elliotclowes/Dropbox/Auto/S3 Upload"
S3_BUCKET_NAME="elliotclowes.com"
S3_DESTINATION_PATH="cold"

# Check if the local folder exists
if [ ! -d "$LOCAL_FOLDER_PATH" ]; then
    echo "Error: Local folder $LOCAL_FOLDER_PATH does not exist."
    exit 1
fi

# Function to rename files if they already exist on S3
rename_if_exists() {
    local file_name="$1"
    local file_base=$(basename "$file_name")
    local file_dir=$(dirname "$file_name")
    local s3_key="$S3_DESTINATION_PATH/$file_base"

    # Check if the file exists on S3
    if aws s3 ls "s3://$S3_BUCKET_NAME/$s3_key" > /dev/null 2>&1; then
        # Get current timestamp
        local timestamp=$(date +"%Y-%m-%d %H.%M")
        
        # Rename file by appending timestamp
        local new_file_base="${file_base%.*} - $timestamp.${file_base##*.}"
        local new_file_path="$file_dir/$new_file_base"
        mv "$file_name" "$new_file_path"
        
        echo "$new_file_path"  # Return the new file path
    else
        echo "$file_name"  # Return the original file path if no renaming is needed
    fi
}

# Iterate over all files in the local folder, ignoring files with 'DS_Store'
for file in "$LOCAL_FOLDER_PATH"/*; do
    if [[ "$file" != *"DS_Store"* ]]; then
        # Rename the file if it already exists on S3
        new_file_path=$(rename_if_exists "$file")
        
        # Upload the file to S3
        aws s3 cp "$new_file_path" "s3://$S3_BUCKET_NAME/$S3_DESTINATION_PATH/" --only-show-errors
        
        if [ "$?" -eq 0 ]; then
            echo "Uploaded $new_file_path successfully."
        else
            echo "Error: Failed to upload $new_file_path."
        fi
    fi
done

# Delete the files locally, ignoring files containing 'DS_Store'
find "$LOCAL_FOLDER_PATH" -type f ! -name "*DS_Store*" -delete
if [ "$?" -eq 0 ]; then
    echo "Files deleted locally successfully."
else
    echo "Error: Could not delete files locally."
    exit 1
fi
