setopt localoptions extendedglob clobber
integer idx is_locked counter=0
local busyfile busywith

__zconvey_usage_zc-all() {
    pinfo2 "Sends command to all unbusy sessions (also busy when -f passed)"
    pinfo "Usage: zc-all [-h|--help] [-f|--force] [-a|--ask] [-q|--quiet] [-v|--verbose] COMMAND ARGUMENT ..."
    print -- "-h/--help                - this message"
    print -- "-q/--quiet               - don't output status messages"
    print -- "-v/--verbose             - output more status messages"
    print -- "-a/--ask                 - ask for command (if not provided)"
}

local -A opthash
zparseopts -D -A opthash h -help q -quiet v -verbose f -force a -ask || { __zconvey_usage_zc-all; return 1; }

integer verbose=0 quiet=0 force=0 ask=0

# Help
(( ${+opthash[-h]} + ${+opthash[--help]} )) && { __zconvey_usage_zc-all; return 0; }

# ASK (requests command and/or ID)
(( ask = ${+opthash[-a]} + ${+opthash[--ask]} ))
if [ "$ask" = "0" ]; then
    local ask_setting
    zstyle -b ":plugin:zconvey" ask ask_setting || ask_setting="no"
    [ "$ask_setting" = "yes" ] && ask=1 || ask=0
fi

# VERBOSE, QUIET, FORCE
(( verbose = ${+opthash[-v]} + ${+opthash[--verbose]} ))
(( quiet = ${+opthash[-q]} + ${+opthash[--quiet]} ))
(( force = ${+opthash[-f]} + ${+opthash[--force]} ))

local -a args
args=( "${(q)@}" )

local cmd="${args[*]}"
cmd="${cmd//\\;/;}"
cmd="${cmd//\\|/|}"
cmd="${cmd//\\&/&}"
cmd="${cmd##[[:space:]]#}"
cmd="${cmd%%[[:space:]]#}"

# Resupply missing input if requested
if (( $ask )); then
    # Supply command?
    if [[ -z "$cmd" ]]; then
        vared -cp "Enter command to send: " cmd
        cmd="${cmd##[[:space:]]#}"
        cmd="${cmd%%[[:space:]]#}"
        if [ -z "$cmd" ]; then
            pinfo "No command enterred, exiting"
            return 0
        fi
    fi
fi

if [ -z "$cmd" ]; then
    pinfo "No command provided, aborting"
    return 1
fi

for (( idx = 1; idx <= 100; idx ++ )); do
    name=""
    busywith=""
    is_locked=0

    __zconvey_is_session_active "$idx" && is_locked=1 || is_locked=0

    if (( is_locked )); then
        busyfile="$ZCONVEY_OTHER_DIR/${idx}.busy"
        if [[ -e "$busyfile" && "$idx" != "$ZCONVEY_ID" ]]; then
            busywith="\033[1;33m$(<$busyfile)\033[0m"

            __zconvey_get_name_of_id "$idx"
            if (( force )); then
                counter+=1
                (( quiet )) || print "Sending to busy session $idx (name: $REPLY, busy with: $busywith)"
                zc -qi "$idx" -r "${cmd[@]}"
            else
                (( quiet )) || print "Session $idx (name: $REPLY) busy ($busywith)"
            fi
        elif [[ "$idx" != "$ZCONVEY_ID" ]]; then
            counter+=1
            if (( verbose )); then
                zc -i "$idx" -r "${cmd[@]}"
            else
                zc -qi "$idx" -r "${cmd[@]}"
            fi
        fi
    fi
done

(( quiet )) || pinfo "Sent command to $counter other sessions"

return 0

# vim:ft=zsh
