#!/bin/sh

#include XDG directory paths; we'll need the "Pictures" directory path
. "$HOME"/.config/user-dirs.dirs

success_count=0
failure_count=0

if [ $# -lt 2 ]; then
    echo "Usage: $0 EXTENSION [FILE]..." > /dev/stderr
    exit 1
else
    new_extension="$1"
    shift
fi

path_exists() {
[ -e "$1" ]
}

path_is_writeable() {
# implies existence
[ -w "$1" ]
}

inkscape_export() {
# usage: inkscape_export "/path/to/vector.svg" "/path/to/export.png"
# requires $new_extension to be exported prior to calling the function
    inkscape_output=$(inkscape --without-gui --file="$1" --export-"$new_extension"="$2" 2>&1)
    if [ $? -eq 0 ]; then
        success_count=$(($success_count + 1))
        return 0
    else
        notify-send --icon=dialog-error --urgency=critical "Failed to export $1" "$inkscape_output"
        failure_count=$(($failure_count + 1))
        return 1
    fi
}

while [ -n "$1" ]; do
    directory=$(dirname "$1")
    new_filename=$( basename "$1" | rev | cut -d '.' -f 2- | rev )
    new_full_name="$directory/$new_filename.$new_extension"
    if path_is_writeable "$directory" || path_is_writeable "$new_full_name"; then
        inkscape_export "$1" "$new_full_name"
    else
        inkscape_export "$1" "$XDG_PICTURES_DIR/$new_filename" && \
            notify-send --icon=dialog-warning "Could not write to $new_full_name" "Exported image was saved to your Pictures folder."
    fi
    shift
done

# report success, but only if there were no failures
# because notify-osd drops notifications if they're sent with a small interval
# and we don't want failure notifications to be dropped
if [ $failure_count -eq 0 ]; then
    if [ $success_count -eq 0 ]; then
        : #pretend we are not here
    elif [ $success_count -eq 1 ]; then
        notify-send --icon=inkscape --urgency=low "File exported."
    else
        notify-send --icon=inkscape --urgency=low "$success_count files exported."
    fi
fi
