#!/bin/bash

# Check if the correct number of arguments is provided
if [ "$#" -ne 2 ]; then
    echo "Usage: $0 <in_folder> <out_folder>"
    exit 1
fi

IN_FOLDER="$1"
OUT_FOLDER="$2"

# Check if the input and output folders exist
if [ ! -d "$IN_FOLDER" ]; then
    echo "Input folder does not exist: $IN_FOLDER"
    exit 1
fi

if [ ! -d "$OUT_FOLDER" ]; then
    echo "Output folder does not exist: $OUT_FOLDER"
    exit 1
fi

# Iterate over each file in the input folder
for IN_FILE in "$IN_FOLDER"/*; do
    # Extract the base name of the file (without extension)
    BASE_NAME=$(basename "$IN_FILE")
    BASE_NAME="${BASE_NAME%.*}"

    # Search for a file with the same base name in the output folder and its subfolders
    OUT_FILE=$(find "$OUT_FOLDER" -type f -name "${BASE_NAME}.*")

    if [ -n "$OUT_FILE" ]; then
        # Extract the extension of the output file
        OUT_EXT="${OUT_FILE##*.}"

        # Convert the input file to the same format as the output file
        magick "$IN_FILE" "${OUT_FILE%.*}.$OUT_EXT"

        echo "Replaced $OUT_FILE with converted $IN_FILE"
    else
        echo "No matching file found in output folder for $BASE_NAME"
    fi
done
