# shellcheck shell=bash disable=SC2142,SC2154

alias shodan:data:ret='{ [ -z "$data" ] || ___x_cmd_pipevar data x j2y >&2; return 1; }'


# Section: Interactive judge
___x_cmd_shodan_is_not_interactive_env() {
    ! ___x_cmd_is_stdout2tty
}

___x_cmd_shodan_is_interactive_env(){
    ___x_cmd_is_stdout2tty
}

# EndSection


# shellcheck shell=dash
___x_cmd_shodan_qstr_(){
    x_=
    local op="$1";      shift
    case "$op" in
        # --hostname|--port|--country|--city|--org|--isp|--product|--version|--geo|--before|--after|--net)
        --*)
            x_="${op#--}: \"$2\""
            ;;
        *)
            N=shodan M="Unknown [option=$op]" log:ret:64 ;;
    esac
}


___x_cmd_shodan_linecount_(){
    local line
    x_=0

    if [ $# -eq 0 ]; then
        while read -r line; do
            [ -n "$line" ] || break
            x_="$((x_+1))"
        done

    else
        printf "%s\n" "$@" | while read -r line; do
            [ -n "$line" ] || break
            x_="$((x_+1))"
        done
    fi
}

___x_cmd_shodan___getip_(){
    shodan:info "Fetching the IP of the [host=$ip]"

    local ips=
    ips="$(x ip query "$ip")" || {
        shodan:warn "Abort because of no IP found."
        return 1
    }

    local x_
    ___x_cmd_shodan_linecount_ "$ips"

    case "$x_" in
        0)      x_=""
                shodan:warn "Abort because of no IP found for [host=$ip]." ;;
        1)      x_="$ips" ;;
        *)
                shodan:info "[Total=$x_] IP found for [host=$ip]. Please pick one to check."
                x_=""
                ___x_cmd storeread_ x pick printf "%s\n" "$ips"  || return
    esac
}

___x_cmd_shodan___j2y2pick(){
    x j2y | x pick
}
