#!/bin/bash
DIR=$(dirname $(realpath "$0"))
PROG="$DIR/../main"
PATH_TEST_SYNTAX="$DIR/test_syntax.txt"
PATH_TEST_EXEC="$DIR/test_exec.txt"

is_comment() {
    local line="$1"
    LINE_START=$(echo "$line" | cut -b1)
    [ "$LINE_START" == "#" ] && return 0
    return 1
}

is_section_name() {
    local line="$1"
    LINE_START=$(echo "$line" | cut -b1,2)
    [ "$LINE_START" == "#!" ] && return 0
    return 1
}

#arg1: testname;
#arg2: progkey(-[x]);
#arg3: readfile.
make_test() {
    local testname="$1"
    local progkey="$2"
    local inputfile="$3"
    [ ${#progkey} -gt 2 ] && {
        echo "Test-$testname error: len(progkey) > 2" >&2
        exit 1
    }
    # 'read -r' and 'IFS': ignore esc-seq and SPC as word-delim
    while IFS= read -r line; do
        if is_comment "$line"; then
            if is_section_name "$line"; then
                section="$line"
            else
                comment="$line"
            fi
            continue
        fi
        #The line after the comments should be an input to the PROG
        INPUT="$line"

        last_2b=$(echo "$line" | rev | cut -b 1,2)
        last_byte=$(echo "$last_2b" | cut -b 1)

        while [[ $last_2b != '\\' ]] && [[ $last_byte == '\' ]]; do
            read -r line
            INPUT="$INPUT
$line"
            last_byte=$(echo "$line" | rev | cut -b 1)
        done

        RES=$(echo "$INPUT" | "$PROG" "$progkey" 2>&1)
        # cut all newlines
        RES=$(echo "$RES" | paste -sd' ')
        #
        read -r line
        #
        if [ "$RES" != "$line" ]; then
            if [[ ${line} =~ ^Error.* ]] && [[ $RES =~ ${line}.* ]]; then
                continue
            fi
            echo -e "Test($testname): \033[1;31mfailed\033[0m"
            echo '  \'
            echo "$section"
            echo "$comment"
            echo "> $INPUT"
            echo -e "\033[1;31mGOT:\033[0m"
            echo "$RES"
            echo -e "\033[1;32mEXPECTED:\033[0m"
            echo "$line"

            #for debugging
            echo "$INPUT" > ../keys.txt
            exit 1
        fi
    done < "$inputfile"
    echo -e "Test($testname):\t\033[1;32mpassed\033[0m"
}

echo
make_test "syntax" "-s" "$PATH_TEST_SYNTAX"
make_test "exec" "" "$PATH_TEST_EXEC"

exit 0
