/* BdfServer - Copyright (c) 2025 Vincent Calame - Exemole
 * Logiciel libre donné sous triple licence :
 * 1) selon les termes de la CeCILL V2
 * 2) selon les termes de l’EUPL V.1.1
 * 3) selon les termes de la GNU GPLv3
 * Voir le fichier licences.txt
 */


package fr.exemole.bdfserver.tools.zip;

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.conf.ConfConstants;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import net.fichotheque.eligibility.SubsetEligibility;
import net.fichotheque.utils.EligibilityUtils;
import net.mapeadores.util.io.IOUtils;


/**
 *
 * @author Vincent Calame
 */
public class BackupZip {

    private final SubsetEligibility subsetEligibility;
    private final BdfServer bdfServer;

    public BackupZip(BdfServer bdfServer, SubsetEligibility subsetEligibility) {
        this.bdfServer = bdfServer;
        if (subsetEligibility == null) {
            this.subsetEligibility = EligibilityUtils.ALL_SUBSET_ELIGIBILITY;
        } else {
            this.subsetEligibility = subsetEligibility;
        }
    }

    public void zip(ZipOutputStream zipOutputStream) throws IOException {
        File backupDir = bdfServer.getBdfServerDirs().getDir(ConfConstants.VAR_BACKUP);
        if ((backupDir == null) || (!backupDir.isDirectory())) {
            return;
        }
        zipDir(zipOutputStream, backupDir, "backup");
    }

    private void zipDir(ZipOutputStream zipOutputStream, File dir, String path) throws IOException {
        for (File f : dir.listFiles()) {
            if (f.isDirectory()) {
                zipDir(zipOutputStream, f, path + "/" + f.getName());
            } else {
                zipOutputStream.putNextEntry(new ZipEntry(path + "/" + f.getName()));
                try (InputStream is = new FileInputStream(f)) {
                    IOUtils.copy(is, zipOutputStream);
                }
            }
        }
    }

}
