package com.eactive.eai.rms.onl.common.service;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerException;
import org.springframework.context.ApplicationContext;

import com.eactive.eai.common.util.SystemUtil;
import com.eactive.eai.rms.client.util.CommandParser;
import com.eactive.eai.rms.client.util.CommandUtils;
import com.eactive.eai.rms.common.context.MonitoringContext;

@SuppressWarnings({"rawtypes", "unchecked"})
public class EaiCmCronJob implements Job {
	private MonitoringContext monitoringContext;
	
	private static final Logger logger = Logger.getLogger(EaiCmCronJob.class);
	
	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
     //   JobKey jobKey = context.getJobDetail().getKey();

		ApplicationContext appContext = null;
		try {
			appContext = (ApplicationContext)context.getScheduler().getContext().get("applicationContext");
		} catch (SchedulerException e) {
			logger.error("applicationContext get module error",e);
			return ;
		}  
		
		try {
			if (SystemUtil.isDevServer()) {
				logger.info("EaiCmCronJob: 해당 시스템에선 사용할 수 없습니다. ["+ System.getProperty("eai.systemmode") +"]");
				return;
			}
			monitoringContext = (MonitoringContext)appContext.getBean("monitoringContext");
			run();
			
		} catch (Exception e) {
			logger.error("EaiCmCronJob: property module error", e);
			throw new JobExecutionException(e);
		}
		
	}
	
	private void run() throws Exception {
		
		String shell = monitoringContext.getStringProperty("cm.cron.path", "/fsapp/eai/iocm/cron.sh");
		
		String[] command = {"/bin/sh","-c",shell};
        CommandParser parser = new CommandParser() {
            public Object parse(String string) {
                int result = 0;
                int resultIndex = 0;
                int lineIndex = 0;
                try {
                	resultIndex = string.indexOf("result=") + 7;
                    lineIndex = string.indexOf("\n");
                    result = Integer.parseInt(string.substring(resultIndex,lineIndex));
                } catch (Exception e) {
                	//취약점소스 수정 2020.08.27
                	logger.error(" error", e); 
                }
                return result;
            }
        };

        int result = 0;

        try {
            result = (Integer) CommandUtils.processExec(command, parser);
        } catch (Exception e) {
            logger.warn(e.getMessage());
        }

	}
	


}
