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

import cn.reghao.bnt.common.docker.Docker;
import cn.reghao.bnt.common.docker.DockerImpl;
import cn.reghao.bnt.common.docker.model.DockerAuth;
import lombok.extern.slf4j.Slf4j;

import java.io.File;

/**
 * 打包为 docker 应用
 *
 * @author reghao
 * @date 2019-10-14 22:02:04
 */
@Slf4j
public class DockerPack implements CodePacker {
    private final String targetPath;
    private final Docker docker;

    public DockerPack(String targetPath, DockerAuth dockerAuth) {
        this.targetPath = targetPath;
        this.docker = new DockerImpl(dockerAuth);
    }

    public DockerPack(String targetPath) {
        this.targetPath = targetPath;
        this.docker = new DockerImpl();
    }

    @Override
    public String pack(String appId, String commitId, String appRootPath, String dockerfile) throws Exception {
        int idx = targetPath.lastIndexOf("/");
        String appId1 = targetPath.substring(idx+1);
        String repo;
        if (appId1.equals(appId)) {
            repo = targetPath;
        } else {
            repo = targetPath + File.separator + appId;
        }

        //String repo = targetPath + File.separator + appId;
        String image = repo + ":" + commitId;
        docker.build(image, appRootPath, dockerfile);
        return image;
    }

    @Override
    public String push(String localPath) throws Exception {
        docker.push(localPath);
        return localPath;
    }
}
