#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <sys/types.h>
#include <sys/stat.h>

#include "embedded_device.h"
#include "employee.h"
#include "util.h"
#include "proxy.h"
#include "proxysetup.h"


static char* BIN_NAME = "SignatureProxy";

static sgx_enclave_id_t global_eid = 0;

void syntax_exit(void) {
    char* syntax =
        "SignatureProxy Version 0.0.0\n"
        "Syntax: %s <command> <arguments>\n"
        "\n"
        "Commands:\n"
        "%s"
        "\n"
        "%s"
        "\n"
        "%s"
        "\n"
        "%s";

    printf(syntax, BIN_NAME, proxysetup_syntax(), employee_syntax(), proxy_syntax(), embedded_device_syntax());
    exit (EXIT_FAILURE);
}

void set_bin_name(char* bin_name) {
    BIN_NAME = bin_name;
}

typedef struct _sgx_errlist_t {
    sgx_status_t err;
    const char *msg;
    const char *sug; /* Suggestion */
} sgx_errlist_t;

/* Error code returned by sgx_create_enclave */
static sgx_errlist_t sgx_errlist[] = {
    {
        SGX_ERROR_UNEXPECTED,
        "Unexpected error occurred.",
        NULL
    },
    {
        SGX_ERROR_INVALID_PARAMETER,
        "Invalid parameter.",
        NULL
    },
    {
        SGX_ERROR_OUT_OF_MEMORY,
        "Out of memory.",
        NULL
    },
    {
        SGX_ERROR_ENCLAVE_LOST,
        "Power transition occurred.",
        "Please refer to the sample \"PowerTransition\" for details."
    },
    {
        SGX_ERROR_INVALID_ENCLAVE,
        "Invalid enclave image.",
        NULL
    },
    {
        SGX_ERROR_INVALID_ENCLAVE_ID,
        "Invalid enclave identification.",
        NULL
    },
    {
        SGX_ERROR_INVALID_SIGNATURE,
        "Invalid enclave signature.",
        NULL
    },
    {
        SGX_ERROR_OUT_OF_EPC,
        "Out of EPC memory.",
        NULL
    },
    {
        SGX_ERROR_NO_DEVICE,
        "Invalid SGX device.",
        "Please make sure SGX module is enabled in the BIOS, and install SGX driver afterwards."
    },
    {
        SGX_ERROR_MEMORY_MAP_CONFLICT,
        "Memory map conflicted.",
        NULL
    },
    {
        SGX_ERROR_INVALID_METADATA,
        "Invalid enclave metadata.",
        NULL
    },
    {
        SGX_ERROR_DEVICE_BUSY,
        "SGX device was busy.",
        NULL
    },
    {
        SGX_ERROR_INVALID_VERSION,
        "Enclave version was invalid.",
        NULL
    },
    {
        SGX_ERROR_INVALID_ATTRIBUTE,
        "Enclave was not authorized.",
        NULL
    },
    {
        SGX_ERROR_ENCLAVE_FILE_ACCESS,
        "Can't open enclave file.",
        NULL
    },
};

/* Check error conditions for loading enclave */
void sgx_print_error_message(sgx_status_t ret)
{
    size_t idx = 0;
    size_t ttl = sizeof sgx_errlist/sizeof sgx_errlist[0];

    for (idx = 0; idx < ttl; idx++) {
        if(ret == sgx_errlist[idx].err) {
            if(NULL != sgx_errlist[idx].sug)
                printf("Info: %s\n", sgx_errlist[idx].sug);
            printf("Error: %s\n", sgx_errlist[idx].msg);
            break;
        }
    }
    
    if (idx == ttl)
    	printf("Error code is 0x%X. Please refer to the \"Intel SGX SDK Developer Reference\" for more details.\n", ret);
}

int initialize_enclave(char* token_path) {
    FILE* sgx_token_file = NULL;
    sgx_launch_token_t token = {0};
    sgx_status_t ret;
    int updated = 0;

    if (token_path != NULL) {
        sgx_token_file = fopen(token_path, "rb");
    }

    if(sgx_token_file == NULL){
        if (errno != ENOENT && token_path != NULL) {
            perror("Error opening sgx token file");
            exit(1);
        }
    }else{
        size_t read_num = fread(token, 1, sizeof(sgx_launch_token_t), sgx_token_file);
        if (read_num != 0 && read_num != sizeof(sgx_launch_token_t)) {
            fprintf(stderr, "sgx token file is corrupted");
            return (1);
        }
    }

    ret = sgx_create_enclave("enclave.signed.so", SGX_DEBUG_FLAG, &token, &updated, &global_eid, NULL);
    if (ret != SGX_SUCCESS) {
        sgx_print_error_message(ret);
        return (1);
    }

    if (updated && token_path != NULL) {
        sgx_token_file = freopen(token_path, "wb", sgx_token_file);
        if(sgx_token_file == NULL){
            perror("Error opening sgx token file");
            return (1);
        }
        size_t write_num = fwrite(token, 1, sizeof(sgx_launch_token_t), sgx_token_file);
        if (write_num != sizeof(sgx_launch_token_t)){
            fprintf(stderr,"Warning: Failed to save launch token to \"%s\".\n", token_path);
            return (1);
        }
    }
    return (0);
}

sgx_enclave_id_t get_global_eid(void){
    return global_eid;
}

int load_file(const char* path, uint8_t** data, size_t* data_len) {
    FILE* file;
    size_t file_size;
    uint8_t* buf;

    int file_des = open(path, O_RDWR);
    if(file_des == 0)
        return (1);

    struct stat stat;
    if (fstat(file_des, &stat) != 0){
        close(file_des);
        return (2);
    }

    close(file_des);

    file_size = stat.st_size;
    buf = malloc(file_size);
    if (buf == NULL)
        return (3);

    file = fopen(path, "rb");
    if(file == NULL){
        free(buf);
        return (4);
    }

    if (fread(buf, file_size, 1, file) != 1 || ferror(file) != 0) {
        free(buf);
        fclose(file);
        return (5);
    }

    fclose(file);
    *data = buf;
    *data_len = file_size;
    return (0);
}
