#!/bin/bash

input="$1"  # Replace with your input directory path
output_dir="$2"  # Replace with your output directory path

# Ensure the output directory exists or create it
mkdir -p "$output_dir"

split_img() {
    file=$1
    filename=$(basename "$file")
    filename_without_extension="${filename%.*}"
    extension="${filename##$filename_without_extension}"
    output_file1="$output_dir/${filename_without_extension}_left${extension}"
    output_file2="$output_dir/${filename_without_extension}_right${extension}"

    # Get the width of the image
    width=$(identify -format "%w" "$file")

    # Use ImageMagick to split the image in half
    magick "$file" -crop "50%x100%+0+0" "$output_file1"
    magick "$file" -crop "50%x100%+$((width / 2))+0" "$output_file2"

    echo "Split $filename into $output_file1 and $output_file2"
}

# Loop through all JPEG files in the input directory
if [[ -d $input ]]; then
    echo "Processing images in directory: $input"
    for file in "$input/*.(jpg|jpeg|png)"; do
        if [ -e "$file" ]; then
            split_img "$file"
        fi
    done
else
    split_img $input
fi

echo "Splitting completed."

