package cn.reghao.devops.logstash;

import cn.reghao.devops.logstash.config.ConfigFile;
import cn.reghao.devops.logstash.config.LogFile;
import cn.reghao.devops.logstash.config.LogstashConfig;
import cn.reghao.devops.logstash.service.FileReader;
import cn.reghao.jutil.jdk.serializer.JsonConverter;
import cn.reghao.jutil.jdk.util.SingleInstance;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.List;

/**
 * @author reghao
 * @date 2023-11-08 10:34:51
 */
@Slf4j
public class LogStashApp {
    static void shutdownGracefully() {
        Runtime.getRuntime().addShutdownHook(new Thread(new ShutdownHook(), "main-shutdown-hook"));
    }

    static class ShutdownHook implements Runnable {
        @Override
        public void run() {
            log.info("资源清理完成，结束 devops-logstash...");
        }
    }

    public static void main(String[] args) {
        if (args.length != 1) {
            log.error("必须指定配置文件...");
            return;
        }

        String configFilePath = ConfigFile.configFilePath(args[0], LogStashApp.class);
        LogstashConfig logstashConfig = JsonConverter.jsonFileToObject(new File(configFilePath), LogstashConfig.class);
        String wsUrl = logstashConfig.getWsUrl();
        List<LogFile> logFiles = logstashConfig.getLogFiles();
        FileReader fileReader = new FileReader(wsUrl, logFiles);
        fileReader.start();

        shutdownGracefully();
        SingleInstance.onlyOne(60002);
    }
}
