#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <linux/limits.h>
#include <hiperiso_define.h>
#include <hiperiso_util.h>
#include <hiperiso_json.h>
#include <hiperiso_disk.h>
#include <hiperiso_http.h>

char g_log_file[PATH_MAX];
char g_ini_file[PATH_MAX];

int hiperiso_log_init(void);
void hiperiso_log_exit(void);

void hiperiso_signal_stop(int sig)
{
    vlog("hiperiso server exit due to signal ...\n");
    printf("hiperiso server exit ...\n");
    
    hiperiso_http_stop();
    hiperiso_http_exit();
    hiperiso_disk_exit();
    hiperiso_log_exit();
    exit(0);
}

int main(int argc, char **argv)
{
    int i;
    int rc;
    const char *ip = "127.0.0.1";
    const char *port = "24680";

    if (argc != 3)
    {
        printf("Invalid argc %d\n", argc);
        return 1;
    }

    if (isdigit(argv[1][0]))
    {
        ip = argv[1];
    }
    
    if (isdigit(argv[2][0]))
    {
        port = argv[2];
    }

    snprintf(g_log_file, sizeof(g_log_file), "log.txt");
    snprintf(g_ini_file, sizeof(g_ini_file), "./Hiperiso2Disk.ini");
    for (i = 0; i < argc; i++)
    {
        if (argv[i] && argv[i + 1] && strcmp(argv[i], "-l") == 0)
        {
            snprintf(g_log_file, sizeof(g_log_file), "%s", argv[i + 1]);
        }
        else if (argv[i] && argv[i + 1] &&  strcmp(argv[i], "-i") == 0)
        {
            snprintf(g_ini_file, sizeof(g_ini_file), "%s", argv[i + 1]);
        }
    }

    hiperiso_log_init();

    vlog("===============================================\n");
    vlog("===== Hiperiso2Disk %s %s:%s =====\n", hiperiso_get_local_version(), ip, port);
    vlog("===============================================\n");

    hiperiso_disk_init();

    hiperiso_http_init();
    
    rc = hiperiso_http_start(ip, port);
    if (rc)
    {
        printf("Hiperiso failed to start http server, check log.txt for detail\n");
    }
    else
    {
        signal(SIGINT, hiperiso_signal_stop);
        signal(SIGTSTP, hiperiso_signal_stop);
        signal(SIGQUIT, hiperiso_signal_stop);
        while (1)
        {
            sleep(100);
        }
    }
    
    return 0;
}

