# shellcheck shell=dash
___x_cmd_depend___main(){
    [ "$#" -gt 0 ] ||   set -- -h

    local op="$1"; shift
    case "$op" in
        watch|run|__run_needupdate|__run_go)
            ___x_cmd_depend_"$op" "$@"
            ;;
    esac
}

___x_cmd_depend_run(){
    ! ___x_cmd_depend___run_needupdate "$@" || ___x_cmd_depend___run_go "$@"
}

___x_cmd_depend_watch(){
    local MAX=-1
    local INTERVAL=2
    while [ "$#" -gt 0 ]; do
        case "$1" in
            -m)     MAX="$2";       shift 2 ;;
            -i)     INTERVAL="$2";  shift 2 ;;
            *)      break
        esac
    done

    while [ "$MAX" -gt 0 ]; do
        while ! ___x_cmd_depend___run_needupdate "$@"; do
            ___x_cmd_cmds_sleep "$INTERVAL" || return 130
        done
        ___x_cmd_depend___run_go "$@"

        [ "$MAX" -le 0 ] ||  MAX=$((MAX-1))
    done
}

# x depend final.md -- a.md b.md -- eval '___comdine a.md b.md final.md'
___x_cmd_depend___run_needupdate(){
    local targetfile="$1";  shift
    [ "$1" != -- ]          || shift
    while [ $# -gt 0 ]; do
        case "$1" in
            --)     return 1 ;;
            *)      [ -f "$1" ] || N=depend M="Dependent file not found. [fp=$1]" log:ret:1
                    [ "$targetfile" -nt "$1"  ] || return 0
        esac
        shift
    done
    return 1
}

___x_cmd_depend___run_go(){
    shift 1
    [ "$1" != -- ] ||       shift
    while [ "$#" -gt 0 ]; do
        case "$1" in
            --)     shift; break ;;
            *)      shift ;;
        esac
    done

    [ "$#" -eq 0 ] || "$@"
}
