# shellcheck shell=dash
___x_cmd_humantime___main(){
    local op="$1"; shift
    case "$op" in
        -h|--help)
            x help -m humantime 1>&2
            return 1 ;;
        sec|sec_|tosec|tosec_|in)
            "___x_cmd_humantime_${op}" "$@"
            ;;
        *)
            ___x_cmd_humantime_sec_ "$@"
        ;;
    esac
}


___x_cmd_humantime_sec(){
    local x_
    ___x_cmd_humantime_sec_ "$@"
    printf "%s\n" "$x_"
}

___x_cmd_humantime_sec_(){
    local arg="${1:?Provide second argument}"
    local frac=""
    case "$arg" in
        *.*)    frac="${arg#*.}"; frac="${frac:+".$frac"}";
                arg="${arg%%.*}" ;;
    esac

    local res
    x_=""

    res="$(( arg % 60 ))"
    [ -z "$res" ] || x_="${res}${frac}s${x_}"
    arg="$((arg / 60))"
    [ "$arg" -gt 0 ] || return 0

    res="$(( arg % 60 ))"
    [ -z "$res" ] || x_="${res}m${x_}"
    arg="$(( arg / 60 ))"
    [ "$arg" -gt 0 ] || return 0

    res="$(( arg % 24 ))"
    [ -z "$res" ] || x_="${res}h${x_}"
    arg="$(( arg / 24 ))"
    [ "$arg" -gt 0 ] || return 0

    x_="${arg}d${x_}"
    ___X_CMD_HUMANTIME_SEC_="$x_"   # Remove in the future
}


___x_cmd_humantime_tosec(){
    local x_
    ___x_cmd_humantime_tosec_ "$@"
    printf "%s\n" "$x_"
}

___x_cmd_humantime_tosec_(){
    local human="${1}"
    local res=0
    local num

    while [ -n "$human" ]; do
        if [ "$human" != "${human#*d}" ]; then
            num="${human%%d*}"
            res=$(( res + num * 24 * 60 * 60 ))
            human="${human#*d}"
            continue
        fi

        if [ "$human" != "${human#*h}" ]; then
            num="${human%%h*}"
            res=$(( res + num * 60 * 60 ))
            human="${human#*h}"
            continue
        fi

        if [ "$human" != "${human#*m}" ]; then
            num="${human%%m*}"
            res=$(( res + num * 60 ))
            human="${human#*m}"
            continue
        fi

        if [ "$human" != "${human#*s}" ]; then
            num="${human%%s*}"
            res=$(( res + num ))
            human="${human#*s}"
            continue
        fi

        res=$(( res + human ))
        break
    done

    x_=$res
}

___x_cmd_humantime_in(){
    local date=${1:?Provide human time unit}; shift
    local x_
    ___x_cmd_humantime_tosec_ "$date"

    local i; for i in "$@"; do
        if [ "$i" -ge "$x_" ]; then
            x:debug "Expect within $date($x_) but get $i"
            return 1
        fi
    done
}
