# shellcheck shell=dash

xrc:mod:lib     task   __runcmd

___x_cmd_task___main(){
    [ "$#" -gt 0 ] ||   set -- --help

    local op="$1";      shift
    case "$op" in
        -h|--help)      ___x_cmd help -m task   "$@";    return 0 ;;
        ls|ps|la|\
        run|stop|kill)  ___x_cmd_task_"$op"     "$@" ;;
        *)              N=task M="Unknown subcmd -> $op" log:ret:64 ;;
    esac
}

___x_cmd_task_ls(){
    local namespace="DEFAULT"
    local running=""
    local stopped=""

    while [ $# -gt 0 ]; do
        case "$1" in
            --namespace)        namespace="$2" ; arg:2:shift ;;
            --running)          running=1 ; shift ;;
            --stopped)          stopped=1 ; shift ;;
            --all)              running=1; stopped=1 ; shift ;;
        esac
    done

    local datadir="$___X_CMD_ROOT_DATA/task/namespace/$namespace"

    local x_
    ___x_cmd fsiter --file_ "$datadir"

    local pidfile
    # $DATE-$PPID
    while read -r pidfile; do
        {
            read -r ppid
            read -r startuptime
            read -r pid
            read -r name
            read -r startup
        }<"$pidfile"
    done <<A
$x_
A

}

___x_cmd_task_ps(){
    ___x_cmd_task_ls --running
}

# record the task name, pid, startup, command arguments
# Support subshell
___x_cmd_task_run(){
    local namespace="DEFAULT"
    local running=""
    local stopped=""
    local reason=""

    while [ $# -gt 0 ]; do
        case "$1" in
            --namespace)        namespace="$2" ; arg:2:shift ;;
            --name)             name="$2" ; arg:2:shift ;;
            --reason)           reason="$2" ; arg:2:shift ;;
            --)                 shift ; break ;;
        esac
    done

    local datadir="$___X_CMD_ROOT_DATA/task/namespace/$namespace"


    local process_id
    process_id="$( trap ":;" HUP ; "$@" & printf "%s\n" "$!")"

    # First using the pid.

    {
        printf "%s\t" "$process_id" "$$" "$name" "$timeofdate"
        printf "%s\n" "$reason"
    } >"$datadir/PROCESS_LIST.tsv"
}

___x_cmd_task_stop(){
    :
}

___x_cmd_task_kill(){
    :
}

___x_cmd_task_interrupt(){
    :
}

___x_cmd_task_fork(){
    :
}

