#!/bin/bash

# converta
#
# Run `convert` over a directory and filter files by a particular pattern
#
# Example - Convert all ARW files in ~/Pictures to PNG:
# ./converta -d ~/Pictures -p '.*.ARW' -e PNG

script_name="$(basename -- "$0")"
force=false

function usage() {
    echo "Usage: $script_name [OPTIONS]"
    echo
    echo "Options:"
    echo "  -h              Display help"
    echo "  -d [DIRECTORY]  Directory of files to process"
    echo "  -o [EXTENSION]  Target extension"
    echo "  -l [LEVELS]     Limit the amount of directory levels to process"
    echo "  -p [PATTERN]    Extended regular expression pattern for filtering files"
    echo
    echo "Example:"
    echo "  $script_name -d ~/Pictures -o JPG -l 2 -p '.*.ARW$'"
}

while getopts ":d:o:l:p:fh" arg; do
    case $arg in
    d) directory=$OPTARG ;;
    o) extension=$OPTARG ;;
    l) levels="-maxdepth $OPTARG" ;;
    p) pattern=$OPTARG ;;
    f) force=true ;;
    h)
        usage
        exit 0
        ;;
    :)
        echo "$script_name: Must supply an argument to -$OPTARG." >&2
        usage
        exit 1
        ;;
    ?)
        echo "Invalid option: -${OPTARG}."
        echo
        usage
        exit 2
        ;;
    esac
done

[ -z "$directory" ] && usage && exit 1
[ -z "$extension" ] && usage && exit 1
[ -z "$pattern" ] && usage && exit 1

# Kill ourself with SIGINT upon receiving SIGINT:
trap '
  trap - INT # restore default INT handler
  kill -s INT "$$"
' INT

echo "Will $($force && echo "forcibly ")convert files in '$directory' that match '$pattern' to '$extension'"

# shellcheck disable=SC2086
while read -r input_path; do
    file="$(basename "$input_path")"
    output_path="${input_path%.*}.$extension"
    addl_str=""
    cvt=true
    grep -Eq "$pattern" <<<"$file" || continue

    if [ -f "$output_path" ]; then
        if [ "$(wc -c <"$output_path")" -eq 0 ]; then
            addl_str=" (exists, 0 bytes)"
            rm "$output_path"
        elif ! $force; then
            addl_str=" (already converted)"
            cvt=false
        else
            addl_str=" (overwriting)"
            rm "$output_path"
        fi
    fi

    echo "$input_path -> $output_path$addl_str"
    $cvt && convert "$input_path" "$output_path"
done <<<"$(find "$directory" $levels -type f)"
