#!/bin/bash

show_help() {
    echo "usage: get-failed <PARSED-LOG>"
    echo "       get-successful <PARSED-LOG>"
    echo "       get-aborted <PARSED-LOG>"
    echo "       get-total <PARSED-LOG>"
    echo "       list-failed <PARSED-LOG>"
    echo "       check-rexecution <PARSED-LOG>"
    echo ""
    echo "Get general information about the current system"
}

get_successful() {
    local log="$1"
    TESTS_SUCCESSFUL=$(jq -r '.[] | select( .type == "result") | ( select( .result_type == "Successful") | .number ) // 0 ' "$log" | awk '{s+=$1} END {print s}')
    # shellcheck disable=SC2086
    test $TESTS_SUCCESSFUL -gt 0
    echo "$TESTS_SUCCESSFUL"
}

get_failed() {
    local log="$1"
    TESTS_FAILED=$(jq -r '.[] | select( .type == "result") | ( select( .result_type == "Failed") | .number ) // 0 ' "$log" | awk '{s+=$1} END {print s}')
    # shellcheck disable=SC2086
    test $TESTS_FAILED -gt 0
    echo "$TESTS_FAILED"
}

get_aborted() {
    local log="$1"
    TESTS_ABORTED=$(jq -r '.[] | select( .type == "result") | ( select( .result_type == "Aborted") | .number ) // 0 ' "$log" | awk '{s+=$1} END {print s}')
    # shellcheck disable=SC2086
    test $TESTS_ABORTED -gt 0
    echo "$TESTS_ABORTED"
}

get_total(){
    local log="$1"

    TESTS_SUCCESSFUL=$(get_successful "$log")
    TESTS_FAILED=$(get_failed "$log")
    TESTS_ABORTED=$(get_aborted "$log")
    echo "$((TESTS_SUCCESSFUL+TESTS_FAILED+TESTS_ABORTED))"
}

list_failed(){
    local log="$1"
    jq -r '.[] | select( .type == "result") | select( .result_type == "Failed") | .detail.lines[]' "$log" | cut -d '-' -f2- | xargs
}

check_rexecution() {
    local log="$1"
    TESTS_FAILED=$(get_failed "$log")
    TESTS_ABORTED=$(get_aborted "$log")

    # Aborted cannot be used to determine if we need to re-run all because it could be a aborted suite with
    test "$TESTS_FAILED" != 0 && test "$TESTS_ABORTED" = 0
}


main() {
    if [ $# -eq 0 ]; then
        show_help
        exit 0
    fi

    local subcommand="$1"
    local action=
    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help)
                show_help
                exit 0
                ;;
            *)
                action=$(echo "$subcommand" | tr '-' '_')
                shift
                break
                ;;
        esac
    done

    if [ -z "$(declare -f "$action")" ]; then
        echo "log.analyzer: no such command: $subcommand" >&2
        show_help
        exit 1
    fi

    "$action" "$@"
}

main "$@"
