package xyz.wbsite.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StringUtils;
import xyz.wbsite.frame.utils.FileUtil;
import xyz.wbsite.frame.utils.ZipUtil;
import xyz.wbsite.module.conf.ent.NginxCtrl;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;


@Configuration
public class NginxConfig {

    @Autowired
    private Environment environment;

    @Bean
    public NginxCtrl initNginx() {
        String property = environment.getProperty("nginx-path");
        File nginxHome = null;
        if (StringUtils.isEmpty(property)) {
            ApplicationHome home = new ApplicationHome(getClass());
            // 当前运行jar文件
            File jarFile = home.getSource() != null ? home.getSource() : home.getDir();

            //jar同目录
            nginxHome = new File(jarFile.getParent(), "nginx");

            if (!nginxHome.exists()) {
                ClassPathResource classPathResource = new ClassPathResource("nginx-1.16.1.zip");
                try {
                    InputStream inputStream = classPathResource.getInputStream();
                    File nginxDir = new File(jarFile.getParent(), "nginx");
                    File nginxZip = new File(jarFile.getParent(), "nginx.zip");
                    FileUtil.inputStream2File(inputStream, nginxZip);
                    ZipUtil.unZip(nginxZip, nginxDir);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            nginxHome = new File(property);
        }

        if (!nginxHome.exists()) {
            throw new RuntimeException("nginx home not exists!");
        }

        File start = new File(nginxHome, "start.bat");
        File stop = new File(nginxHome, "stop.bat");
        File reload = new File(nginxHome, "reload.bat");

        NginxCtrl nginxCtrl = new NginxCtrl();
        nginxCtrl.setStartCmd(start.getAbsolutePath());
        nginxCtrl.setStopCmd(stop.getAbsolutePath());
        nginxCtrl.setReloadCmd(reload.getAbsolutePath());
        nginxCtrl.setVersionCmd(nginxHome.getAbsolutePath() + " -v ");
        nginxCtrl.setConfig(new File(new File(nginxHome, "conf"), "nginx.conf"));
        return nginxCtrl;
    }
}
