#!/bin/bash

SCRIPT=$( basename "$0" )
VERSION="1.0.0"
SERVER="${LINUX_SERVER:-localhost}:${LINUX_PORT:-1337}"
TESTSFILE="${TESTS:-tests.csv}"
LOG_LEVEL=0
TEST_COUNT=0

function usage
{
    local txt=(
        "Testing the endpoints of the Bthapp-server"
        "Usage: $SCRIPT [options]"
        ""
        "Options:"
        "  -h, --help       Prints help."
        "  -v, --version    Prints version."
        "  -V, --verbose    Sets logging mode to verbose."
        "  -u, --useful     Sets logging mode to useful."
    )

    printf "%s\n" "${txt[@]}"
}

function badUsage
{
    local message="$1"
    local txt=(
        "For an overview of the command, execute:"
        "$SCRIPT --help"
    )

    [[ $message ]] && printf "$message\n"

    printf "%s\n" "${txt[@]}"
}

function version
{
    local txt=(
        "$SCRIPT version $VERSION"
    )

    printf "%s\n" "${txt[@]}"
}

function error_exit
{
    printf "$1" 1>&2
	exit 1
}

function test
{
    TEST_COUNT=$(($TEST_COUNT + 1))

    local url="$SERVER$1"

    echo "TEST: $TEST_COUNT"

    if (( $LOG_LEVEL == 2)); then
        echo "Contacting \"$url\" looking for: $2, $3"
    else
        echo "$url"
    fi

    local response=$(curl -s -w "\n%{http_code}" "$url")
    local status=$(echo "$response" | tail -1)

    if [ "$status" = "000" ]; then
        echo "FAILED: Could not reach the server."
    else
        local content=$(echo "$response" | head -1)

        if (( $LOG_LEVEL == 0)); then
            echo "$status"
        elif (( $LOG_LEVEL == 1)); then
            echo "$status"
            echo "$content"
        elif (( $LOG_LEVEL == 2)); then
            if [ "$status" = "$2" ]; then
                if [ "$content" = "$3" ]; then
                    echo "PASSED: Great"
                else
                    echo "FAILED: Invalid content: $content"
                fi
            else
                echo "FAILED: Invalid status: $status"
            fi
        else
            echo "WARNING: Invalid log level: $LOG_LEVEL"
        fi
    fi
}

while (( $# ))
do
    case "$1" in
        --help | -h)
            usage
            exit 0
        ;;
        --version | -v)
            version
            exit 0
        ;;
        --verbose | -V)
            LOG_LEVEL=1
            break
        ;;
        --useful | -u)
            LOG_LEVEL=2
            break
        ;;
        *)
            badUsage "Option/command not recognized."
            exit 1
        ;;
    esac
done

echo "Testing the Bthapp-server: $SERVER"
echo "Running in logging mode: $LOG_LEVEL"

while read -r line; do
    IFS=';' read -r -a fields <<< "$line"

    test "${fields[0]}" "${fields[1]}" "${fields[2]}"
done < $TESTSFILE
