package cn.reghao.bnt.web.devops.builder.tool.packer;

import cn.reghao.bnt.web.devops.builder.model.LocalBuildDir;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;

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

/**
 * 静态文件打包
 *
 * @author reghao
 * @date 2025-06-05 14:53:20
 */
@Slf4j
public class StaticPack implements CodePacker {
    // TODO 必须指定构建存在的目录
    private final String binDirname;

    public StaticPack(String binDirname) {
        this.binDirname = binDirname;
    }

    private void createTargetDir(String targetPath) throws IOException {
        File dir = new File(targetPath);
        if (!dir.exists()) {
            FileUtils.forceMkdir(new File(targetPath));
        }
    }

    @Override
    public String pack(String appId, String commitId, String appRootPath, String dockerfile) throws Exception {
        if (binDirname == null) {
            throw new Exception("存放编译产物的目录 binDirname 不能是 null");
        }

        String sourceDirPath = appRootPath + File.separator + binDirname;
        File srcDir = new File(sourceDirPath);
        String targetDirPath = LocalBuildDir.packDir + File.separator + appId;
        createTargetDir(targetDirPath);

        String dirname = String.format("%s_%s", appId, commitId);
        String destDirPath = targetDirPath + File.separator + dirname;
        File destDir = new File(destDirPath);
        if (destDir.exists()) {
            FileUtils.deleteDirectory(destDir);
            log.info("delete exist dir {}", destDirPath);
        }
        FileUtils.copyDirectory(srcDir, destDir);
        return "";
    }

    @Override
    public String push(String localPath) {
        return localPath;
    }
}
