#include <tee_client_api.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

#define PTA_K3_OTP_UUID { 0xacc50f40, 0x0613, 0x4abd, \
    { 0x8d, 0xfe, 0xa9, 0x64, 0xcb, 0x74, 0xeb, 0x69 } }

#define TA_OTP_CMD_READ_MMR  0

int main(int argc, char *argv[])
{
    TEEC_Context ctx;
    TEEC_Session sess;
    TEEC_Operation op = { 0 };
    TEEC_UUID uuid = PTA_K3_OTP_UUID;
    TEEC_Result res;
    uint32_t origin;
    uint32_t mmr_index = 0; /* OTP row index to read */

    if (argc > 1)
        mmr_index = (uint32_t)strtoul(argv[1], NULL, 0);

    res = TEEC_InitializeContext(NULL, &ctx);
    if (res != TEEC_SUCCESS) {
        fprintf(stderr, "TEEC_InitializeContext failed: 0x%x\n", res);
        return 1;
    }

    /* Open session directly to the PTA (no TA binary needed on the filesystem) */
    res = TEEC_OpenSession(&ctx, &sess, &uuid,
                           TEEC_LOGIN_PUBLIC, NULL, NULL, &origin);
    if (res != TEEC_SUCCESS) {
        fprintf(stderr, "TEEC_OpenSession failed: 0x%x, origin 0x%x\n", res, origin);
        TEEC_FinalizeContext(&ctx);
        return 1;
    }

    op.paramTypes = TEEC_PARAM_TYPES(TEEC_VALUE_INPUT,
                                     TEEC_VALUE_OUTPUT,
                                     TEEC_NONE, TEEC_NONE);
    op.params[0].value.a = mmr_index;

    res = TEEC_InvokeCommand(&sess, TA_OTP_CMD_READ_MMR, &op, &origin);
    if (res != TEEC_SUCCESS) {
        fprintf(stderr, "TEEC_InvokeCommand failed: 0x%x, origin 0x%x\n", res, origin);
    } else {
        printf("OTP row[%u] = 0x%08x\n", mmr_index, op.params[1].value.a);
    }

    TEEC_CloseSession(&sess);
    TEEC_FinalizeContext(&ctx);
    return (res == TEEC_SUCCESS) ? 0 : 1;
}