# shellcheck shell=dash

___x_cmd log init man

xrc:mod:lib     man     run ls search all nv k fzf simplecolor remote

___x_cmd_man___main(){
    ___x_cmd hascmd man     ||  N=man M='man command not found' log:ret:1
    [ $# -gt 0 ]            ||  set - --fzf

    local op="$1";  shift
    case "$op" in
        -h|--help)      ___x_cmd help -m man;          return ;;
        "")             ___x_cmd help -m man >&2;      return 64 ;;

        :*)             ___x_cmd tldr "${op#:}"         "$@" ;;
        -k)             ___x_cmd_man___k                "$@" ;;

        -e|--explain)   ___x_cmd mankier explain        "$@" ;;

        --simplecolor)  ___x_cmd_man___simplecolor      "$@" ;;

        # legacy ...
        --ls)           ___x_cmd_man_ls                 "$@" ;;
        -s|--search)    ___x_cmd_man___search           "$@" ;;
        --nv)           ___x_cmd_man___nv               "$@" ;;

        --remote)       ___x_cmd_man_remote             "$@" ;;

        --fzf)          ___x_cmd_man___fzf              "$@" ;;
        --fzdata)       ___x_cmd_man___fz_data          "$@" ;;
        *)              ___x_cmd_man___open "$op"     "$@" ;;
    esac
}


___x_cmd_man___open(){
    if ___x_cmd_man_run "$@"; then
        return 0
    fi

    # Try remote if on ubuntu or arch linux
    if ___x_cmd os is linux; then
        case "$(cat /etc/os-release 2>/dev/null | head -1)" in
            *Ubuntu*|*Arch*)
                man:info "Man page not found locally, trying remote..."
                ___x_cmd_man_remote --ubuntu "$@"   && return 0 ;;

            *)  man:info "Man page not found locally, trying remote archlinux manpage source."
                ___x_cmd_man_remote --arch  "$@"    && return 0 ;;
        esac
    fi

    man:info "Cannot locate the document. Using the fuzzy search."
    ___x_cmd_man___search "$@"
}

