/*
 * Copyright (c) 2021 Samsung Electronics Co., Ltd All Rights Reserved
 *
 * PROPRIETARY/CONFIDENTIAL
 *
 * This software is the confidential and proprietary information of Samsung
 * Electronics Co., Ltd. ("Confidential Information"). You shall not disclose such
 * Confidential Information and shall use it only in accordance with the terms of
 * the license agreement you entered into with Samsung Electronics Co., Ltd. ("SAMSUNG")
 * SAMSUNG MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE
 * SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT
 * NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SAMSUNG SHALL NOT BE
 * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
 * MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */

#include <inttypes.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>

#include "CDsms.h"
#include "IDsms_invoke.h"
#include "CDsms_open.h"
#include "object.h"

#define LOG_TAG "[DSMSTA-INTERFACE]"
#include "dsmsta_log.h"

#include "qsee_fs.h"
#include "qsee_prng.h"
#include "qsee_sfs.h"

#define NONCE_BYTES_LEN 8
#define NONCE_STRING_LEN 21

// This implementation does not require a context, so "retain" and
// "release" are no-ops.
#define CDsms_release(ctx) Object_OK
#define CDsms_retain(ctx)  Object_OK

static inline int32_t
CDsms_send_msg(void *ctx, const void *input_ptr, size_t input_len)
{
	int fd, ret;
	uint64_t nonce;
	uint8_t bytes[NONCE_BYTES_LEN];
	char filename[NONCE_STRING_LEN];

	LOGD("CDsms_send_msg");

	if (qsee_prng_getdata(bytes, NONCE_BYTES_LEN) != NONCE_BYTES_LEN) {
		LOGE("Error occurred generating random bytes");
		return Object_ERROR;
	}

	memcpy(&nonce, bytes, sizeof(uint64_t));

	if (snprintf(filename, NONCE_STRING_LEN, "%" PRIu64, nonce) < 0) {
		LOGE("Error occurred generating nonce");
		return Object_ERROR;
	}

	fd = qsee_sfs_open(filename, O_CREAT | O_RDWR | O_TRUNC);
	if (!fd) {
		LOGE("Error occurred while opening file");
		return Object_ERROR;
	}

	LOGD("Writing to SFS file %s: '%s'", filename, (char *)input_ptr);

	ret = qsee_sfs_write(fd, (char *)input_ptr, input_len);
	if (ret != input_len) {
		LOGE("Error occurred while writing to file");
		return Object_ERROR;
	}

	qsee_sfs_close(fd);

	return Object_OK;
}

static IDsms_DEFINE_INVOKE(CDsms_invoke, CDsms_, void *)

int32_t
CDsms_open(Object cred, Object *objOut)
{
	*objOut = (Object) {CDsms_invoke, NULL};

	return Object_OK;
}
