# shellcheck shell=dash disable=SC2030,SC2031

# Default: modifiled
# Cannot work for folder: The modified time attribute of folder keep updating.

# x fileage --in 1d -m LICENSE == x humantime in 1d "$(x fileage -m LICENSE)"
# x fileage

# x fileage -lt 1d -m LICENSE
# x fileage -gt 1d -m LICENSE
# x fileage -lt lm -m LICENSE

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

    local op="$1";  shift
    case "$op" in
        --help|-h)              ___x_cmd help -m fileage        "$@"    ;;

        --get_)                 ___x_cmd_fileage___get_         "$@"    ;;
        --stat)                 ___x_cmd_fileage_stat           "$@"    ;;
        --in)                   ___x_cmd_fileage___in           "$@"    ;;
        *)                      ___x_cmd_fileage___exec  "$op"  "$@"    ;;
    esac
}

___x_cmd_fileage___in(){
    local current=""; current="$(date +%s)"
    local date="$1"
    [ -n "$date" ] || { ___x_cmd log :fileage error -h 'x fileage --in <human_time_unit e.g 1d> <file_path>' "Provide human time unit"; return 64; }
    shift 1
    local x_="";   ___x_cmd humantime tosec_ "$date"

    local ts=""
    ___x_cmd_fileage_stat "$@" | while read -r ts; do
        [ -n "$ts" ] || {
            ___x_cmd log :fileage error "Get fileage failure. Please check the file exists. TS=$ts"
            local IFS=" "; x log :fileage error "filelist ==> $*"
            return 1
        }
        [ "$((current - ts))" -le "$x_" ] || return 1
    done
}

___x_cmd_fileage___exec(){
    local current="";   current="$(date +%s)"
    local human="";     [ "$1" != -H ] || { shift;  human=1; }
    ___x_cmd_fileage_stat "$@" | while read -r ts; do
        [ -n "$ts" ] || {
            ___x_cmd log :fileage error "Get fileage failure. Please check the file exists. TS=$ts";
            local IFS=" "; x log :fileage error "filelist ==> $*"
            return 1
        }
        if [ -z "$human" ]; then
            printf "%s\n" "$((current - ts))"
        else
            local x_="";   ___x_cmd humantime sec_ "$((current - ts))"
            printf "%s\n" "$x_"
        fi
    done
}

___x_cmd_fileage___get_(){
    if ___x_cmd_fileage_stat_ "$@"; then
        local current; current="$(date +%s)"
        x_="$((current - x_))"
    else
        x_=
        return 1
    fi
}

# deprecated
___x_cmd_fileage_(){
    ___x_cmd_fileage___get_ "$@"
}
