#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/stat.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[MAX_PATH];
char g_cur_dir[MAX_PATH];
char g_hiperiso_dir[MAX_PATH];

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();
#ifndef HIPERISO_SIM    
    hiperiso_www_exit();
#endif
    hiperiso_disk_exit();
    hiperiso_log_exit();
    exit(0);
}

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

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

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

    strlcpy(g_hiperiso_dir, argv[3]);
    scnprintf(g_log_file, sizeof(g_log_file), "%s/%s", g_hiperiso_dir, LOG_FILE);
    hiperiso_log_init();

    getcwd(g_cur_dir, MAX_PATH);

    if (!hiperiso_is_directory_exist("./hiperiso"))
    {
        printf("%s/hiperiso directory does not exist\n", g_cur_dir);
        return 1;
    }

    hiperiso_get_disk_info(argv);    

    vlog("===============================================\n");
    vlog("===== Hiperiso Plugson %s:%s =====\n", ip, port);
    vlog("===============================================\n");

    hiperiso_disk_init();
#ifndef HIPERISO_SIM
    rc = hiperiso_www_init();
    if (rc)
	{
		printf("Failed to init web data, check log for details.\n");
		hiperiso_disk_exit();
		hiperiso_log_exit();
		return 1;
	}
#endif
    hiperiso_http_init();
    
    rc = hiperiso_http_start(ip, port);
    if (rc)
    {
        printf("Hiperiso failed to start http server, check ./hiperiso/plugson.log 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;
}

