/*
 * Copyright 2022 Red Hat, Inc. and/or its affiliates
 * and other contributors as indicated by the @author tags.
 *
 * 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.jboss.uninstaller;

import org.jboss.uninstaller.utils.JarUtils;
import org.jboss.installer.actions.ActionException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.jar.Attributes;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;

public class UninstallerDataWriter {

    private final Path targetPath;
    private Path uninstallPath;
    private Path sourcePath;

    public UninstallerDataWriter(Path targetPath, Path sourcePath) throws ActionException {
        this.targetPath = targetPath;
        this.sourcePath = sourcePath;
        init();
    }

    private void init() throws ActionException {
        try {
            uninstallPath = targetPath.resolve("uninstaller");
            Files.createDirectories(uninstallPath);
        } catch (IOException e) {
            throw new ActionException("Failed to create directory uninstaller:", e);
        }
    }
    public void createJar() throws ActionException {

        Manifest manifest = new Manifest();
        manifest.getMainAttributes().put(Attributes.Name.IMPLEMENTATION_TITLE, " Compiler");
        manifest.getMainAttributes().put(Attributes.Name.IMPLEMENTATION_VENDOR, "Red Hat");
        manifest.getMainAttributes().put(Attributes.Name.IMPLEMENTATION_VERSION, "8");
        manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, UninstallerWrapper.class.getName());
        manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");

        try (FileOutputStream outputStream = new FileOutputStream(uninstallPath + File.separator + "uninstaller.jar");
            JarOutputStream jarOutputStream = new JarOutputStream(outputStream, manifest)) {
            if(Files.isDirectory(sourcePath)) {
                JarUtils.jarDirectory(sourcePath, jarOutputStream);
            } else {
                JarUtils.addJar(jarOutputStream, sourcePath);
            }
            JarUtils.addUninstallerPropertyFile(targetPath, jarOutputStream);
            jarOutputStream.finish();
        } catch (IOException e) {
            throw new ActionException(e.getMessage(), e);
        }
    }
}
