# shellcheck shell=dash

___x_cmd_osv_ls(){
    [ "$#" -gt 0 ] ||   set - --app

    local op="$1"; shift
    case "$op" in
        -h|--help)      ___x_cmd help -m osv ls;    return 0 ;;
        --app)          ___x_cmd_osv_ls___app           "$@" ;;
        --csv)          ___x_cmd_osv_ls___csv           "$@" ;;
        --json)         ___x_cmd_osv_ls___json          "$@" ;;
        --co|,)         X_CO_MSHOT_CMD="x osv ls" ___x_cmd co --mshot "$@" ;;
        *)              ___x_cmd_osv_ls___app "$op"     "$@" ;;
    esac
}


___x_cmd_osv_ls___app(){
    ___x_cmd_osv_ls___csv "$@" \
        | ___x_cmd csv app  \
            --width "40%,10%,10%,-,-,-,-,-,-,-,-,-,-,-,-,-,-"    \
            --table-width 40%                                    \
            --preview id,updated,timeCreated,timeStorageClassUpdated,kind,selfLink,mediaLink,bucket,generation,metageneration,contentType,storageClass,md5Hash,crc32c
}

___x_cmd_osv_ls___csv(){
    ___x_cmd ccmd -- ___x_cmd_osv_ls___csv_raw "$@"
}

___x_cmd_osv_ls___csv_raw(){
    ___x_cmd_osv_ls___raw "$@"      \
        | ___x_cmd jo 2c             \
            .name .size .etag .updated                \
            .timeCreated  .timeStorageClassUpdated    \
            .id .kind .selfLink .mediaLink .bucket    \
            .generation .metageneration .contentType  \
            .storageClass .md5Hash .crc32c            \
        | ___x_cmd csv header --add  \
            name size etag updated                    \
            timeCreated  timeStorageClassUpdated      \
            id kind selfLink mediaLink bucket         \
            generation metageneration contentType     \
            storageClass md5Hash crc32c
}

___x_cmd_osv_ls___json(){
    ___x_cmd ccmd -- ___x_cmd_osv_ls___json_ "$@"
}
___x_cmd_osv_ls___json_(){
    ___x_cmd_osv_ls___raw "$@" | ___x_cmd jo fmt
}

___x_cmd_osv_ls___raw(){
    # prefix="GitHub%20Actions"
    local prefix="$1"

    local x_=; ___x_cmd_osv___str_encode_spaces_ "$prefix"
    prefix="$x_"

    # Try to list ...
    {
        if [ -z "$prefix" ]; then
            ___x_cmd curl "https://storage.googleapis.com/storage/v1/b/osv-vulnerabilities/o?matchGlob=**.json"
        else
            ___x_cmd curl "https://storage.googleapis.com/storage/v1/b/osv-vulnerabilities/o?prefix=${prefix}&matchGlob=**.json"
        fi
    } | ___x_cmd jo 1.items
}

___x_cmd_osv___str_encode_spaces_(){
    x_="$(printf "%s" "$*" | ___x_cmd_cmds_awk '{gsub(/ /,"%20"); print}')"
}
