/*
 * #%L
 * Fuse EAP :: Installer
 * %%
 * Copyright (C) 2015 RedHat
 * %%
 * 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.
 * #L%
 */
package org.jboss.fuse.eap.installer.internal;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.LinkedList;

import org.wildfly.extras.patch.installer.AbstractInstaller;
import org.wildfly.extras.patch.installer.IllegalStateAssertion;
import org.wildfly.extras.patch.installer.Version;

/**
 * Main class that installs the fuse-eap-distro.
 */
public final class Main {

    public static void main(String[] originalArgs) throws Exception {

        AbstractInstaller installer = new AbstractInstaller() {
            public String getJarName() {
                return "fuse-eap-installer.jar";
            }

            @Override
            protected void runInstallCommands() throws IOException, Exception {
                super.runInstallCommands();

                // Write fuse-version.txt
                String resname = "META-INF/fuse.version";
                InputStream resource = Main.class.getClassLoader().getResourceAsStream(resname);
                IllegalStateAssertion.assertNotNull(resource, "Cannot obtain resource: " + resname);
                
                Version version;
                try (BufferedReader br = new BufferedReader(new InputStreamReader(resource))) {
                    version = Version.get(br.readLine().trim());
                } catch (IOException e) {
                    throw new IllegalStateException("Cannot read version metadata", e);
                }
                File outfile = eapHome.resolve("fuse-version.txt").toFile();
                try (PrintWriter pw = new PrintWriter(new FileWriter(outfile))) {
                    String line = "Red Hat Fuse Integration Platform - Version " + version;
                    pw.println(line);
                    info(line);
                } catch (IOException e) {
                    throw new IllegalStateException("Cannot write version metadata", e);
                }
            }
        };
        installer.main(new LinkedList<>(Arrays.asList(originalArgs)));
    }
}
