#!/bin/bash

echo "Device IP: " $1
echo "Device name: " $2
echo "Qt5 bins folder path: " $3

if [ $# -lt 3 ]; then
    echo "Enter IP/device name and path to Qt Build folder! EXAMPLE: ./gui_test_script-1.sh 10.204.0.240 integrity-qc8155p-1 /home/target/tests/auto"
    exit 1;
fi

if [[ (! -v MULTI) || (-z "$MULTI") ]]; then
    echo "MULTI application path is not set"
    exit 1
fi

if [[ (! -v DYNAMIC_PROJECT) || (-z "$DYNAMIC_PROJECT") ]]; then
    echo "GHS Dynamic project path is not set"
    exit 1
fi

if [[ (! -v MULTI_COMMAND_FILE) || (-z "$MULTI_COMMAND_FILE") ]]; then
    echo "Multi Commands file path is not set"
    exit 1
fi

# MUST SET MANUALLY in ENV
echo "MULTI binary path: " $MULTI
echo "MULTI dynamic test project path: " $DYNAMIC_PROJECT
echo "MULTI commands file path: " $MULTI_COMMAND_FILE

# the example
#export MULTI=/home/tatiana/sa8155/es7/es7_dev_env/hlos_dev_boot/apps/ghs_apps_proc/multi/multi
#export DYNAMIC_PROJECT=/home/tatiana/MyProjects/Project1
#export MULTI_COMMAND_FILE=/home/tatiana/sa8155/es7/es7_dev_env/multi_commands

#set device ip
IP_STRING=$1

#set device name for accessing to reboot operation
DEVICE_NAME=$2

# set folder path
AUTOTESTS_DIR=$3;

PASS_DIR="./PASSED"
FAIL_DIR="./FAILED"
SKIPPED_DIR="./SKIPPED"

if [ ! -d "$SKIPPED_DIR" ]; then
    mkdir $SKIPPED_DIR
else
    rm -rf $SKIPPED_DIR/* #clean dir
fi

if [ ! -d "$FAIL_DIR" ]; then
    mkdir $FAIL_DIR
else
    rm -rf $FAIL_DIR/* #clean dir
fi

if [ ! -d "$PASS_DIR" ]; then
    mkdir $PASS_DIR
else
    rm -rf $PASS_DIR/* #clean dir
fi

# file contains Multi output for each loaded project
LOCAL_TEST_RESULT='autotestresult.txt'
if [ -f "$LOCAL_TEST_RESULT" ]; then
    rm $LOCAL_TEST_RESULT
fi

TESTS_COUNTER_FILE='Final_Report.txt'
if [ -f "$TESTS_COUNTER_FILE" ]; then
    rm $TESTS_COUNTER_FILE
fi

passed_counter=0
failed_counter=0

run_image_on_device() {
    # ALWAYS REBOOTING before each binary test
    ssh -i /home/qt/.ssh/test_farm_id_rsa -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null qt@10.204.0.42 python /home/qt/hardware-controller-scripts/switchlogic.py --poweroff $DEVICE_NAME
    sleep 4
  
    ssh -i /home/qt/.ssh/test_farm_id_rsa -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null qt@10.204.0.42 python /home/qt/hardware-controller-scripts/switchlogic.py --poweron $DEVICE_NAME
    # waiting system boot time
    sleep 20

    # let's ping TARGET -> even if target is ON, it doesn't mean network is alive. Always need to check.
    ping -c 1 $IP_STRING &> /dev/null && target_alive=1 || target_alive=0
                
    echo "target_alive = " $target_alive
                        
    # Check if board doesn't wake up
    while [[ $target_alive -eq 0 ]];
    do                  
        echo "REBOOTING THE BOARD $DEVICE_NAME"

        # REBOOTING
        ssh -i /home/qt/.ssh/test_farm_id_rsa -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null qt@10.204.0.42 python /home/qt/hardware-controller-scripts/switchlogic.py --poweroff $DEVICE_NAME
    
        sleep 4

        ssh -i /home/qt/.ssh/test_farm_id_rsa -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null qt@10.204.0.42 python /home/qt/hardware-controller-scripts/switchlogic.py --poweron $DEVICE_NAME

        # waiting system boot time
        sleep 20

        # let's ping TARGET -> even if target is ON, it doesn't mean network is alive. Always need to check.
        ping -c 1 $IP_STRING &> /dev/null && target_alive=1 || target_alive=0

        if [ $try_to_reboot -eq 20 ]; then
            echo "The device $IP_STRING is not answering!!!"
            exit 1
        fi
                     
        try_to_reboot=$[ $try_to_reboot + 1 ]
    done
   
    # build test elf image
    timeout -k 3 12m $MULTI $DYNAMIC_PROJECT/default.gpj -build myproject &

    # need time before building and loading
    sleep 3
    
    # load image dynamically to the board
    timeout -k 3 12m $MULTI $DYNAMIC_PROJECT/dbg/bin/myproject -connect="rtserv2 $IP_STRING" -p $MULTI_COMMAND_FILE &
    
    # wait quitall command from MULTI_COMMAND_FILE
    wait < <(jobs -p)
}

test_qt_submodule_dir () {

    if [ -d $1 ]; then
        folders_list=$1$2
        target_alive=0
        try_to_reboot=0

        for i in $folders_list
        do
            try_to_reboot=0
            folder_name=$(basename $i)
            binary_file=$i/tst_$3$folder_name

            if [[ -f "$binary_file" ]]; then
                echo "$binary_file needs to be tested."
                run_image_on_device_counter=0

                # replace qt test binary path inside myproject.int, line 12
                sed -i "12s|.*|  Filename $binary_file|g" $DYNAMIC_PROJECT/src/myproject.int

                while [[ $run_image_on_device_counter -lt 5 ]];
                do  
                    run_image_on_device
    
                    if [[ -f "$LOCAL_TEST_RESULT" ]]; then
                        break
                    fi
                    run_image_on_device_counter=$[ $run_image_on_device_counter + 1 ]
                    echo "Binary $binary_file was not loaded. Retry count = $run_image_on_device_counter"
                done 

                # calculate test results
                test_result=`cat "$LOCAL_TEST_RESULT"`
                    
                # search if fails
                if [[ ! -f "$LOCAL_TEST_RESULT" ]]; then
                    echo $folder_name " SKIPPED (cannot load) "
                    test_result_file="$SKIPPED_DIR/$folder_name.txt"
                elif [[ $test_result == *", 0 failed"* ]]; then
                    passed_counter=$[ $passed_counter + 1 ]
                    echo $folder_name " PASSED "
                    test_result_file="$PASS_DIR/$folder_name.txt"
                else
                    failed_counter=$[ $failed_counter + 1 ]
                    echo $folder_name " FAILED "
                    test_result_file="$FAIL_DIR/$folder_name.txt"
                 fi

                # save result into appropriate folder
                cat "$LOCAL_TEST_RESULT" >> $test_result_file

                # remove temporary file
                rm $LOCAL_TEST_RESULT
               
                # after each test binary we must reboot the board
                target_alive=0
             fi
        done
    else
        echo "Error: Directory " "$1" " does not exist."
    fi
}


# second argument is test directories deepness: ./ or ./../ or ./../../
# folder
test_qt_submodule_dir "$AUTOTESTS_DIR" "/*/*/*/*/*/*/*/"
test_qt_submodule_dir "$AUTOTESTS_DIR" "/*/*/*/*/*/*/"
test_qt_submodule_dir "$AUTOTESTS_DIR" "/*/*/*/*/*/"
test_qt_submodule_dir "$AUTOTESTS_DIR" "/*/*/*/*/"
test_qt_submodule_dir "$AUTOTESTS_DIR" "/*/*/*/"
test_qt_submodule_dir "$AUTOTESTS_DIR" "/*/*/"
test_qt_submodule_dir "$AUTOTESTS_DIR" "/*/"

# some submodules have different binaries naming: starting from 'q' letter 
# look at $3 parameter in func test_qt_submodule_dir
test_qt_submodule_dir "$AUTOTESTS_DIR" "/*/*/*/*/*/*/*/" "q"
test_qt_submodule_dir "$AUTOTESTS_DIR" "/*/*/*/*/*/*/" "q"
test_qt_submodule_dir "$AUTOTESTS_DIR" "/*/*/*/*/*/" "q"
test_qt_submodule_dir "$AUTOTESTS_DIR" "/*/*/*/*/" "q"
test_qt_submodule_dir "$AUTOTESTS_DIR" "/*/*/*/" "q"
test_qt_submodule_dir "$AUTOTESTS_DIR" "/*/*/" "q"
test_qt_submodule_dir "$AUTOTESTS_DIR" "/*/" "q"

    
# save counted fail/pass to file
echo "Tested dir: $3 "  >> $TESTS_COUNTER_FILE
echo "PASSED: $passed_counter test binaries"  >> $TESTS_COUNTER_FILE
echo "FAILED: $failed_counter test binaries"  >> $TESTS_COUNTER_FILE


