/*
 * Copyright (C) 2015-2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#define TLOG_TAG "secure-storage"

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

#include <interface/storage/storage.h>
#include <lib/tipc/tipc.h>
#include <lk/err_ptr.h>
#include <trusty_log.h>

#include "aidl_service.h"
#include "block_cache.h"
#include "crypt.h"
#include "ipc.h"
#include "proxy.h"
#include "storage_limits.h"
#include "error_reporting.h"

#define SS_ERR(args...) fprintf(stderr, "ss: " args)

int main(void) {
    struct proxy_connect_context ctx = {
            .service = STORAGE_SERVICE_INITIAL_VALUE(.service),
            .tipc_ctx = {.ops = {.on_connect = proxy_connect}},
    };
    uint32_t acl_flags = IPC_PORT_ALLOW_TA_CONNECT | IPC_PORT_ALLOW_NS_CONNECT;

    crypt_init();
    block_cache_init();

    struct tipc_hset* hset = tipc_hset_create();
    if (IS_ERR(hset)) {
        TLOGE("Failed to create handle set (%d)\n", PTR_ERR(hset));
        return EXIT_FAILURE;
    }

    int rc = ipc_port_create(hset, &ctx.tipc_ctx, STORAGE_DISK_PROXY_PORT, 1,
                             STORAGE_MAX_BUFFER_SIZE, acl_flags);
    if (rc < 0) {
        SS_ERR("fatal: unable to initialize proxy endpoint (%d)\n", rc);
        return rc;
    }

    rc = connect_metrics_ta();
    if(rc != NO_ERROR)
    {
        SS_ERR("fatal: unable to connect to metrics TA (%d)\n", rc);
        return rc;
    }
    rc = tipc_run_event_loop(hset);
    proxy_destroy(&ctx);
    return rc;
}
