#!/bin/bash

NUM_OF_LED=""
NUM_OF_LED_State=2
FILE_PATH="/usr/sbin/mx-led-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_led <num_of_Indexs>"
        exit 1
fi

NUM_OF_LED=$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 Index format
bash $FILE_PATH -i 00 >/dev/null 2>&1
test_fail_result $? "Test 2: Invalid Index format"

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

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

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

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

# Test 7: Get all Index State
for ((i = 0; i < $NUM_OF_LED; ++i)); do
        result=$(bash $FILE_PATH -i $i)
        test_pass_result $(
                [[ "$result" == *"state: off"* ]] ||
                        [[ "$result" == *"state: on"* ]]
                echo $?
        ) "Test 7: Get Index $i State"
done

# Test 8: Set all Index State on
for ((i = 0; i < $NUM_OF_LED; ++i)); do
        bash $FILE_PATH -i $i on >/dev/null 2>&1
        if [[ $? -ne 0 ]]; then
                test_pass_result 1 "Test 8: Set Index $i State on"
                continue
        fi

        result=$(bash $FILE_PATH -i $i)
        test_pass_result $(
                [[ "$result" == *"state: on"* ]]
                echo $?
        ) "Test 8: Set Index $i State on"
done

# Test 9: Set all Index State off
for ((i = 0; i < $NUM_OF_LED; ++i)); do
        bash $FILE_PATH -i $i off >/dev/null 2>&1
        if [[ $? -ne 0 ]]; then
                test_pass_result 1 "Test 8: Set Index $i State off"
                continue
        fi

        result=$(bash $FILE_PATH -i $i)
        test_pass_result $(
                [[ "$result" == *"state: off"* ]]
                echo $?
        ) "Test 8: Set Index $i State off"
done
