package cn.reghao.autodop.common.util.compression;

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;

import java.io.*;

/**
 * 归档
 *
 * @author reghao
 * @date 2020-01-14 10:51:48
 */
public class TarFiles {
    private static final int BUFSIZE = 1024;
    private static String basePath = "";

    public static void tar(String srcPath, String dstPath) throws IOException {
        File srcFile = new File(srcPath);
        File dstFile = new File(dstPath);

        // 归档文件解开后不是一个目录
        if (srcFile.isDirectory()) {
            basePath = srcFile.getAbsolutePath();
        }

        TarArchiveOutputStream taos = new TarArchiveOutputStream(new FileOutputStream(dstFile));
        taos.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
        archive(basePath, srcFile, taos);
        taos.flush();
        taos.close();
    }

    /**
     * @param
     * @return
     * @date 2020-01-14 上午10:53
     */
    public static void archive(String basePath, File srcFile, TarArchiveOutputStream taos) throws IOException {
        if (srcFile.isDirectory()) {
            archiveDir(basePath, srcFile, taos);
        } else {
            archiveFile(basePath, srcFile, taos);
        }
    }

    public static void archiveDir(String basePath, File srcFile, TarArchiveOutputStream taos) throws IOException {
        File[] files = srcFile.listFiles();
        assert files != null;
        if (files.length == 0) {
            // 空目录
            TarArchiveEntry entry = new TarArchiveEntry(srcFile.getAbsolutePath().split(basePath)[1] + "/");
            taos.putArchiveEntry(entry);
            taos.closeArchiveEntry();
        }

        for (File file : files) {
            archive(basePath, file, taos);
        }
    }

    public static void archiveFile(String basePath, File srcFile, TarArchiveOutputStream taos) throws IOException {
        TarArchiveEntry entry = new TarArchiveEntry(srcFile.getAbsolutePath().split(basePath)[1]);
        entry.setSize(srcFile.length());
        taos.putArchiveEntry(entry);

        BufferedInputStream in = new BufferedInputStream(new FileInputStream(srcFile));
        int cnt;
        byte[] data = new byte[BUFSIZE];
        while ((cnt = in.read(data, 0, BUFSIZE)) != -1) {
            taos.write(data, 0, cnt);
        }
        in.close();
        taos.closeArchiveEntry();
    }
}
