#!/usr/bin/bash
# Attach files to Thunderbird Composer

log_error() {
    printf 'thunderbird-compose: %s\n' "$1" >&2
    if command -v logger >/dev/null 2>&1; then
        logger -p user.err -t thunderbird-compose -- "$1"
    fi
}

# Encode each byte so spaces, commas, quotes and Unicode stay within one URI.
file_uri() {
    local LC_ALL=C
    local path=$1 uri=file:// character encoded index
    for ((index = 0; index < ${#path}; index++)); do
        character=${path:index:1}
        case $character in
            [a-zA-Z0-9/._~-]) uri+=$character ;;
            *)
                printf -v encoded '%%%02X' "'$character"
                uri+=$encoded
                ;;
        esac
    done
    printf '%s' "$uri"
}

attachments=""
for file in "$@"; do
    if [[ ! -f "$file" ]]; then
        log_error "Not a regular file: $file"
        exit 1
    fi
    [[ "$file" = /* ]] || file=$PWD/$file
    [[ -z "$attachments" ]] || attachments+=,
    attachments+=$(file_uri "$file")
done

if [[ -z "$attachments" ]]; then
    exec /usr/bin/thunderbird.real -compose
fi
exec /usr/bin/thunderbird.real -compose "attachment='$attachments'"
