#!/usr/bin/bash
#shellcheck disable=SC1090

. "$(sfpath)" || exit 3

shellfu import pretty

shellfu import bmo_qtask


usage() {
    mkusage "$@" \
        "[options] DATA" \
        "[options] -f [FILE]" \
        -o \
            "-f [FILE]   Read DATA from file FILE or standard input if" \
            "            FILE is not specified."                        \
            "-l          Just list plugins available."                  \
            "-n          Don't add any tasks, just show TTDL definition"\
            "-p PLUGIN   Use plugin PLUGIN."                            \
        -- \
        "Use a plugin to create one or more TaskWarrior tasks based on" \
        "information from DATA.  The plugin can specify tags, due dates"\
        "and various other properties."
}


do_action() {
    #
    # Do necessary action $Action
    #
    local ttdl
    local es=0
    ttdl=$(mktemp -t bmo-qtask-ttdl.XXXXXXXX)
    if bmo_qtask__define "$PluginModule" > "$ttdl";
    then
        case $Action in
            add)        <"$ttdl" bmo_qtask__exec; es=$? ;;
            showdef)    cat "$ttdl" >&2 ;;
        esac
    else
        es=3
    fi
    rm "$ttdl"
    return $es
}

main() {
    local BMO_QTASK_DATA
    local file
    local from=args
    local Action=add
    local PluginName
    local PluginModule
    #shellcheck disable=SC2209
    while true; do case $1 in
        -f) from=file; file=$2; break ;;
        -n) Action=showdef; shift ;;
        -p) PluginName=$2; shift 2 || usage -w "no PLUGIN?" ;;
        -l) bmo_qtask__find_plugins | sort; exit $? ;;
        -*) usage -w "unknown argument: $1" ;;
        *)  break ;;
    esac done
    case $from in
        args)
            BMO_QTASK_DATA="$1"
            debug -v BMO_QTASK_DATA
            test -n "$BMO_QTASK_DATA" || usage -w "no DATA?"
            ;;
        file)
            case "$file" in
                "")
                    BMO_QTASK_DATA=$(</dev/stdin)
                    test -n "$BMO_QTASK_DATA" || die "no data provided on standard input"
                    ;;
                *)
                    debug -v file
                    test -f "$file" || die "no such file: $file"
                    test -r "$file" || die "file not readable: $file"
                    BMO_QTASK_DATA=$(< "$file")
                    test -n "$BMO_QTASK_DATA" || die "data file is empty: $file"
                    ;;
            esac
            ;;
    esac
    test -n "$PluginName" && PluginModule=bmo_qtask_$PluginName
    test -n "$PluginModule" \
     || PluginModule=$(bmo_qtask__choose_plugin) \
     || die "could not choose plugin"
    debug -v PluginName PluginModule Action
    do_action
}


main "$@"
