_be_list_targeted() {
        target_ids=""
        for i in $(be list --severity=target | sed 's/.* //'); do
                target_ids="$target_ids $(be target --resolve $i)"
        done

        bugs_with_target=""
        for i in $target_ids; do
                bugs_with_target="$bugs_with_target $(be list -i -e BLOCKS:$i)"
        done

        echo $bugs_with_target | sed 's/ /\n/g' | sort -u
}

_be_list_targeted_and_targets() {
        target_ids=""
        for i in $(be list --severity=target -i); do
                target_ids="$target_ids $i"
        done
        for i in $(_be_list_targeted); do
                target_ids="$target_ids $i"
        done

        echo $target_ids | sed 's/ /\n/g' | sort -u
}

be-list-bugs() {
        # no argument given
        if [ "x$1" = "x" ]; then
                be list -e BLOCKS:$(be set target)
                return;
        fi

        case "$1" in
        -b|--backlog)
                bug_ids=$(diff -u <(_be_list_targeted_and_targets) <(be list -i | sort -u) | grep '^+bdb' | sed 's/^+//')
                for i in $bug_ids; do
                        be show -c $i
                done
                ;;
        -h|--help)
                echo "$FUNCNAME               — list all issues for the current target"
                echo "$FUNCNAME -b|--backlog  — list all issues with no set target (ie, in the backlog)"
                echo "$FUNCNAME TARGET_NAME   — list all issues for the target with the given name"
                ;;
        *)
                be list -e BLOCKS:$(be target --resolve "$1")
        esac
}

_be_list_targets() {
        be list --severity=target | sed 's/.* //g' | sort -n
}

be-list-targets() {
        # no argument given
        if [ "x$1" = "x" ]; then
                _be_list_targets
                return;
        fi

        case "$1" in
        -s|--summary)
                count=0
                for i in $(_be_list_targets); do
                        if [ $count -gt 0 ]; then
                                echo
                        fi

                        echo $i
                        echo "------------------------------"
                        be-list-bugs $i

                        ((count++))
                done
                ;;
        *|-h|--help)
                echo "$FUNCNAME               — all targets"
                echo "$FUNCNAME -s|--summary  — include a summary of tasks for each target"
                ;;
        esac
}
