#!/bin/bash

options=()  # the buffer array for the parameters
eoo=0       # end of options reached
output=0    # do we try to write to file
target=()   # where do we try to write to
fd_for_stdout=63 # some (hopefuly) unused FD, later redirected to stdout

while [[ $1 ]]; do
    if ! ((eoo)); then
        case "$1" in
            --import)
                # ignore all the options and only collect file name(s) - if any
                shift
                exec qubes-gpg-import-key "$@"
                ;;
            # Keyserver options makes no sense for offline GPG VM, so it is
            # rejected by qubes-gpg-client and qubes-gpg-server. But since
            # it is forced by Torbirdy extension, simply ignore the option.
            --keyserver-options)
                shift 2
                ;;
            --yes)
                shift
                ;;
            -o)
                output=1
                target="$2"
                shift 2
                ;;
            --output)
                output=1
                target="$2"
                shift 2
                ;;
            --status-fd|\
            --logger-fd|\
            --attribute-fd)
                if [ "x$2" = "x1" ]; then
                    # don't use stdout for status fd, since it might be later
                    # redirected to a file with --output
                    options+=( "$1" "$fd_for_stdout" )
                    shift 2
                else
                    options+=( "$1" )
                    shift
                fi
                ;;    
            --)
                eoo=1
                options+=("$1")
                shift
                ;;
            *)
                options+=("$1")
                shift
                ;;
        esac
    else
        options+=("$1")
        shift
    fi
done

. /etc/profile.d/qubes-gpg.sh
# 63 is $fd_for_stdout but bash seems to reject variables here
if  ! (($output)) || [ "$target" = "-" ] ; then
    exec qubes-gpg-client "${options[@]}" 63>&1
else
    exec qubes-gpg-client "${options[@]}" 63>&1 >"$target"
fi
