#include "access_control.h"
#include "driver_log.h"

/**
 * @brief Compare two uuids
 * @param [in] a,b uuids
 * @return 1 if uuids are equal and 0 if otherwise
 */
static uint32_t IsUuidsEqual(const TEE_UUID *a, const TEE_UUID *b) {
  int32_t res = TEE_MemCompare(a, b, sizeof(TEE_UUID));

  return (res == 0 ? 1 : 0);
}

uint32_t AccessControlIsAllowedOperation(Operation operation) {
  TEE_UUID caller_uuid = {0};

  TEE_Result status = PlatformGetCallerUuid(&caller_uuid);
  if (status != TEE_SUCCESS) {
    LOG_E("Can not obtain current caller UUID.\n");
    return 0;
  }

  if (operation == kAuthentication) {
    // Authentication is allow always
    LOG_D("Authenticate operation is allowed for everyone.\n");
    return 1;
  }

  if (operation == kReadToTrustlet || operation == kWriteFromTrustlet) {
    for (const TEE_UUID **p = AccessControlGetWhitelist(); *p != NULL; ++p) {
      if (IsUuidsEqual(*p, &caller_uuid)) {
        return 1;
      }
    }
  }

  LOG_E("Operation is not allowed for current caller UUID.\n");
  LOG_D("Operation: %d.\n", operation);
  LOGM_D(&caller_uuid, sizeof(caller_uuid));

  return 0;
}
