#!/usr/bin/env bash

##
# NOTE: This test is designed to run in bazel!
##

set -euox pipefail

ZCORE_COMMAND="scripts/vehicle/zcore_safe_command.sh"
TMP_ZCORE_SAFE="/tmp/zcore_safe_command_temp_"$$
BIN_DEPENDENCY="./bin/sanity_checker_cli"

PUFFIN_SANITY_CHECKS="vehicle/puffin/src/resources/scripts/puffin_sanity_checks.sh"
HOME="."
OUTPUT="/tmp/sanity_checks/sanity-check.json"

test_command_exists() {
    if [ -f "${BIN_DEPENDENCY}" ]
    then
        echo "${BIN_DEPENDENCY} found."
    else
        echo "${BIN_DEPENDENCY} not found."
        exit 1
    fi
}

mock_zcore_safe_successful(){
    cat scripts/vehicle/zcore_safe_command.sh > ${TMP_ZCORE_SAFE}
    echo "echo 'mock zcore exiting successfully';" > ${ZCORE_COMMAND}
    chmod +x ${ZCORE_COMMAND}

    trap "
    cat ${TMP_ZCORE_SAFE} > ${ZCORE_COMMAND} # Restore command
    " EXIT
}

mock_zcore_safe_failure(){
    echo "echo 'mock zcore exiting with failure'; exit 1;" > ${ZCORE_COMMAND}
    trap "
    cat ${TMP_ZCORE_SAFE} > ${ZCORE_COMMAND} # Restore command
    " EXIT
}

test_successful_script() {
    remote_command(){
        echo mock sanity checker; return 0;
    }

    mock_zcore_safe_successful

    if HOME="." source ${PUFFIN_SANITY_CHECKS} > /dev/null; then
        echo " Script correctly exited normal execution."
    else
        echo " Script failed execution."
        exit 1
    fi

    if [ "${OUTPUT}" == "${ZOOX_SANITY_CHECK_JSON}" ]; then
        echo " Script successfully set env variable"
    else
        echo " Script failed to set env variable"
        exit 1
    fi
}

test_early_exit_if_zcore_is_running_script() {
    mock_zcore_safe_failure

    if ! HOME="." ${PUFFIN_SANITY_CHECKS} > /dev/null; then
        echo " Script correctly exited when zcore check failed."
    else
        echo " Script failed to exit when zcore check failed."
        exit 1
    fi
}

test_successful_script
test_early_exit_if_zcore_is_running_script
