/*
 * Copyright (c) 2019-2020 Qualcomm Technologies, Inc.
 * All Rights Reserved.
 * Confidential and Proprietary - Qualcomm Technologies, Inc.
 */

#include <cstdint>
#include <cstdio>

#include "QSEEComAPI.h"   // QSEEComAPI Library header
#include "skeleton_cppapp.h" // Common header between CA and TA

extern "C" {
#include "qtee_init.h"  // QTEE off-target environment initialization
}

int main (void)
{
  struct QSEECom_handle *app_handle = NULL; // The application handle.
  static char const ta_name[] = SKELETON_TA_NAME; // The TA name.

  const uint32_t shared_buffer_len = 4096;
  int retval = -1;

  struct cmd_req_t req = {0};
  struct cmd_rsp_t rsp = {0};

  /*
   * Initialize QTEEEmu.
   *
   * A null pointer can be passed to use the default settings. Alternatively, a path to a JSON file
   * specifying desired settings can be provided. See 'qtee_init.h'.
   */
  retval = qtee_emu_init(nullptr);
  if(retval) {
    printf("qtee_emu_init() failed\n");
    return retval;
  }

  // Load the TA. TA_PATH_DEFINE is defined in the offtarget client app builder.
  retval = QSEECom_start_app(&app_handle, TA_PATH_DEFINE, ta_name, shared_buffer_len);
  if(retval != QSEECOM_SUCCESS) {
    printf("QSEECom_start_app() failed\n");
    goto bail;
  }

  // Send a command to the TA
  req.cmd_id = SAMPLE_CMD;
  retval = QSEECom_send_cmd(app_handle, &req, sizeof(struct cmd_req_t), &rsp, sizeof(struct cmd_rsp_t));
  printf("QSEECom_send_cmd() returned %d\n", retval);

  // rsp is only valid if QSEECom_send_cmd returned successfully
  if(retval == QSEECOM_SUCCESS) {
    printf("TA returned rsp_status %d\n", rsp.status);
  }

  // Shutdown the TA, even if QSEECom_send_cmd failed
  QSEECom_shutdown_app(&app_handle);

bail:
  // Deinitialize the QTEE off-target environment
  qtee_emu_deinit();
  return retval;
}
