#!/usr/bin/env bash

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

set -euo pipefail

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

CLEAR_CACHE_SCRIPT="vehicle/puffin/src/resources/scripts/clear_puffin_embed_cache.sh"

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() {
    rm(){
        echo
    }

    mock_zcore_safe_successful

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

test_early_exit_if_zcore_is_running_script() {
    mock_zcore_safe_failure

    if ! HOME="." ${CLEAR_CACHE_SCRIPT} > /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
