#!/bin/bash

NUM_OF_RELAY=""
NUM_OF_RELAY_Mode=2
FILE_PATH="/usr/sbin/mx-relay-ctl"

function test_pass_result {
        if [ $1 -eq 0 ]; then
                echo -e "[\e[32mPASS\e[0m] $2"
        else
                echo -e "[\e[31mFAIL\e[0m] $2"
        fi
}

function test_fail_result {
        if [ $1 -eq 0 ]; then
                echo -e "[\e[31mFAIL\e[0m] $2"
        else
                echo -e "[\e[32mPASS\e[0m] $2"
        fi
}

if [[ $# -ne 1 ]]; then
        echo "test_relay <num_of_Ports>"
        exit 1
fi

NUM_OF_RELAY=$1

# Test 1: Check if tool is installed
test -e $FILE_PATH
test_pass_result $? "Test 1: Check if tool is installed"

# Test 2: Invalid Port format
bash $FILE_PATH -p 00 >/dev/null 2>&1
test_fail_result $? "Test 2: Invalid Port format"

# Test 3: Invalid Port
bash $FILE_PATH -i $NUM_OF_RELAY >/dev/null 2>&1
test_fail_result $? "Test 3: Invalid Invalid Port"

# Test 4: Invalid Mode format
bash $FILE_PATH -i 0 -m 00 >/dev/null 2>&1
test_fail_result $? "Test 4: Invalid Mode format"

# Test 5: Invalid Mode
bash $FILE_PATH -i 0 -m $NUM_OF_RELAY_Mode >/dev/null 2>&1
test_fail_result $? "Test 5: Invalid Invalid Mode"

# Test 6: Only pass Mode parameter
bash $FILE_PATH -m 0 >/dev/null 2>&1
test_fail_result $? "Test 6: Only pass Mode parameter"

# Test 7: Get all Port Mode
for ((i = 0; i < $NUM_OF_RELAY; ++i)); do
        result=$(bash $FILE_PATH -p $i)
        test_pass_result $(
                [[ "$result" == *"Current relay mode is NO interface."* ]] ||
                        [[ "$result" == *"Current relay mode is NC interface."* ]]
                echo $?
        ) "Test 7: Get Port $i Mode"
done

# Test 8: Set all Port Mode to NC
for ((i = 0; i < $NUM_OF_RELAY; ++i)); do
        bash $FILE_PATH -p $i -m 0 >/dev/null 2>&1
        if [[ $? -ne 0 ]]; then
                test_pass_result 1 "Test 8: Set Port $i Mode to NC"
                continue
        fi

        result=$(bash $FILE_PATH -p $i)
        test_pass_result $(
                [[ "$result" == *"Current relay mode is NC interface"* ]]
                echo $?
        ) "Test 8: Set Port $i Mode to NC"
done

# Test 9: Set all Port Mode to NO
for ((i = 0; i < $NUM_OF_RELAY; ++i)); do
        bash $FILE_PATH -p $i -m 1 >/dev/null 2>&1
        if [[ $? -ne 0 ]]; then
                test_pass_result 1 "Test 8: Set Port $i Mode to NO"
                continue
        fi

        result=$(bash $FILE_PATH -p $i)
        test_pass_result $(
                [[ "$result" == *"Current relay mode is NO interface"* ]]
                echo $?
        ) "Test 8: Set Port $i Mode to NO"
done
