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 2020-03-11 13:37:36
 */
@Slf4j
public class ZipPack implements CodePacker {
    // TODO 必须指定构建存在的目录
    private final String binDirname;

    public ZipPack(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;
        String targetDirPath = LocalBuildDir.packDir + File.separator + appId;
        createTargetDir(targetDirPath);

        String filename = String.format("%s_%s.zip", appId, commitId);
        String dest = targetDirPath + File.separator + filename;
        String url = String.format("/api/app/bd/dl/%s", filename);
        ZipFiles.zip(new File(sourceDirPath), dest);
        return url;
    }

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