#include "tz_platform.h"
#include "cmd_handler.h"
#include "sec_apdu.h"

/**
 * Sem app name
 * Modify the app name to your specific app name
 */
char TZ_APP_NAME[] = {"sem"};

cmd_t cmd_buf;
rsp_t rsp_buf;

/**
  @brief
    Data structure

  @param[in]   cmd_id      Requested command
  @param[in]   data        information (could be data or a pointer to the memory that holds the data
  @param[in]   len         if data is ptr to some buffer, len indicates length of the buffer
  @param[in]   test_buf_size  When running crypto test, this indicates the test packet size
*/
void tz_app_cmd_handler(void* cmd, uint32_t cmdlen, void* rsp, uint32_t rsplen) {
    /* Request-response buffers are allocated by non-secure side*/
    /* Add code to process requests and set response (if any)*/
    p_cmd_t    pCmd    = cmd;
    p_rsp_t    pRsp    = rsp;
    uint32_t   cmd_len = cmdlen;
    uint32_t   rsp_len = rsplen;

    LOGD("Sem Trust App started");
    /* Validate buffers. Both rsp & cmd should be allocated despite of further usage */
    if ( (pCmd == NULL) || (pRsp == NULL) || 
         (pCmd->dataLen > MAX_DATA_SIZE) ||
         (cmd_len != sizeof(cmd_t)) || 
         (rsp_len != sizeof(rsp_t)) ) {
        LOGE("Invalid cmd or rsp pointers or size");
        return;
    }

    /* Replicate buffer to avoid of shared memory usage */
    memcpy(&cmd_buf, pCmd, sizeof(cmd_t));
    memcpy(&rsp_buf, pRsp, sizeof(rsp_t));
    pCmd = &cmd_buf;
    pRsp = &rsp_buf;

    cmdHandler(pCmd->cmd_id, pCmd, pRsp);

    /* Copy back rsp buffer to shared memory */
    pRsp = (p_rsp_t) rsp;
    memcpy(pRsp, &rsp_buf, sizeof(rsp_t));
}

/**
  @brief
    Add any app specific initialization code here
    QSEE will call this function after secure app is loaded and
    authenticated
*/
void tz_app_init(void) {
    /*  App specific initialization code*/
}

/**
  @brief
    App specific shutdown
    App will be given a chance to shutdown gracefully
*/
void tz_app_shutdown(void) {
    /* app specific shutdown code*/
    if(is_secure_spi_opened == TRUE){
        LOGI("%s: secure spi opened. call spiClose()", __func__);
        spiClose();
    }
}
