/*
 * Copyright 2021 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.tomee;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.apache.commons.io.IOUtils;

/**
 * @author Gael Lalire
 */
public class TomEEMicroVestigeInstaller {

    private File base;

    public TomEEMicroVestigeInstaller(final File base) {
        this.base = base;
    }

    public void install() throws Exception {
        ZipInputStream zipFile = new ZipInputStream(TomEEMicroVestigeInstaller.class.getResourceAsStream("/home.zip"));
        ZipEntry entry = zipFile.getNextEntry();
        while (entry != null) {
            File entryDestination = new File(base, entry.getName());
            if (entry.isDirectory()) {
                entryDestination.mkdirs();
            } else {
                entryDestination.getParentFile().mkdirs();
                OutputStream out = new FileOutputStream(entryDestination);
                IOUtils.copy(zipFile, out);
                IOUtils.closeQuietly(out);
            }
            zipFile.closeEntry();
            entry = zipFile.getNextEntry();
        }
        File apps = new File(base, "apps");
        apps.mkdirs();
        File entryDestination = new File(apps, "myear.vear");
        OutputStream out = new FileOutputStream(entryDestination);
        IOUtils.copy(TomEEMicroVestigeInstaller.class.getResourceAsStream("/myear.vear"), out);
        IOUtils.closeQuietly(out);

        entryDestination = new File(apps, "mywar.vwar");
        out = new FileOutputStream(entryDestination);
        IOUtils.copy(TomEEMicroVestigeInstaller.class.getResourceAsStream("/mywar.vwar"), out);
        IOUtils.closeQuietly(out);

        out = new FileOutputStream(new File(base, "conf" + File.separator + "server.xml"));
        IOUtils.copy(TomEEMicroVestigeInstaller.class.getResourceAsStream("/server.xml"), out);
        IOUtils.closeQuietly(out);

        out = new FileOutputStream(new File(base, "conf" + File.separator + "tomee.xml"));
        IOUtils.copy(TomEEMicroVestigeInstaller.class.getResourceAsStream("/tomee.xml"), out);
        IOUtils.closeQuietly(out);
    }

}
