﻿#include <stdio.h>
#include <getopt.h>

#include "thread_lora.h"
#include "thread_comm.h"

int f_main_loop = 1;


static int serial_num = 0;
static char logfile[50] = "stderr";

typedef enum {
    PERSON_VIP,
    PERSON_VISITOR,
    PERSON_MANAGER,
} user_type_t;

typedef enum {
    GATE_OPEN_ONCE_OF_IN = 0,
    GATE_OPEN_ONCE_OF_OUT = 3,
} gate_action_t;

typedef enum {
    OPT_LOG = 0,
} opt_t;

struct option app_long_options[] = {
    {"help",        no_argument,            0,      'h'},
    {"version",     no_argument,            0,      'v'},

    {"l",       required_argument,      0,      OPT_LOG}
};

static void show_help() {
    printf("\n--------------------------------------------------------------------------------\n");
    printf("Usage: dls_utili [OPTIONS]\n");
    printf("\n");
    printf("-v, --version         show this app version\n");
    printf("-h, --help            show this help\n");
    printf("\n--------------------------------------------------------------------------------\n");
    printf("--l, --log <files>           select log files or output\n");
}

static int app_getopt(int argc, char **argv) {
    int ret, index;
    opterr = 0;
    index = 0;

    while (1) {
        ret = getopt_long(argc, argv, ":hv", app_long_options, &index);
        if(ret == -1){
            break;
        }
        switch (ret) {
        case 'v':
            printf("DY lora gateway\n");
            printf("%s Version: 1.0.2\n", argv[0]);
            return 0;
        case 'h':
            show_help();
            return 0;
        case OPT_LOG:
            strncpy(logfile, optarg, sizeof(logfile));
            break;
        default:
            printf("%d\n",ret);
            show_help();
            return 0;
        }
    }
    return 0;
}


void main_loop(void)
{
    char *gate_cmd;
    int size;
    while(f_main_loop)
    {
        usleep(10000);

    }
}

void SignalHandler(int signo) {
    if (signo == SIGINT || signo == SIGTERM || signo == SIGPIPE || signo == SIGABRT) {
        f_main_loop = 0;
        printf("***********signo:%d***********\n",signo);
        fflush(stdout);
    }
}


int main(int argc, char** argv)
{
    int ret;
    struct sigaction sig_action;
    sig_action.sa_handler = SignalHandler;
    sig_action.sa_flags = SA_RESTART;
    sigemptyset(&sig_action.sa_mask);
    sigaction(SIGINT, &sig_action, NULL);
    sigaction(SIGTERM, &sig_action, NULL);
    sigaction(SIGABRT, &sig_action, NULL);
    if (app_getopt(argc, argv))
            exit (0);
    printf("*********** running ***********\n");
    openlog("lora", LOG_PID, LOG_DAEMON);
    msg_list_init();
    thread_common_start();
    thread_lora_start(lora_cfg_get());
    main_loop();
    thread_common_stop();
    thread_lora_stop();
    syslog(LOG_NOTICE, "exit");
    closelog();
    printf("*********** exit ***********\n");
    return 0;
}
