/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.karaf.shell.ssh;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Map;

import javax.security.auth.Subject;

import org.apache.felix.service.command.CommandProcessor;
import org.apache.felix.service.command.CommandSession;
import org.apache.felix.service.command.Converter;
import org.apache.karaf.shell.util.ShellUtil;
import org.apache.karaf.util.StreamUtils;
import org.apache.sshd.server.Command;
import org.apache.sshd.server.Environment;
import org.apache.sshd.server.ExitCallback;
import org.apache.sshd.server.SessionAware;
import org.apache.sshd.server.session.ServerSession;

public class ShellCommand implements Command, SessionAware {

    private String command;
    private InputStream in;
    private OutputStream out;
    private OutputStream err;
    private ExitCallback callback;
    private ServerSession session;
    private CommandProcessor commandProcessor;

    public ShellCommand(CommandProcessor commandProcessor, String command) {
        this.commandProcessor = commandProcessor;
        this.command = command;
    }

    public void setInputStream(InputStream in) {
        this.in = in;
    }

    public void setOutputStream(OutputStream out) {
        this.out = out;
    }

    public void setErrorStream(OutputStream err) {
        this.err = err;
    }

    public void setExitCallback(ExitCallback callback) {
        this.callback = callback;
    }

    public void setSession(ServerSession session) {
        this.session = session;
    }

    public void start(final Environment env) throws IOException {
        try {
            final CommandSession session = commandProcessor.createSession(in, new PrintStream(out), new PrintStream(err));
            session.put("SCOPE", "shell:osgi:*");
            session.put("APPLICATION", System.getProperty("karaf.name", "root"));
            for (Map.Entry<String,String> e : env.getEnv().entrySet()) {
                session.put(e.getKey(), e.getValue());
            }
            try {
                Subject subject = this.session != null ? this.session.getAttribute(KarafJaasAuthenticator.SUBJECT_ATTRIBUTE_KEY) : null;
                Object result;
                if (subject != null) {
                    try {
                        result = Subject.doAs(subject, new PrivilegedExceptionAction<Object>() {
                            public Object run() throws Exception {
                                return session.execute(command);
                            }
                        });
                    } catch (PrivilegedActionException e) {
                        throw e.getException();
                    }
                } else {
                    result = session.execute(command);
                }
                if (result != null)
                {
                    session.getConsole().println(session.format(result, Converter.INSPECT));
                }
            } catch (Throwable t) {
                ShellUtil.logException(session, t);
            }
        } catch (Exception e) {
            throw (IOException) new IOException("Unable to start shell").initCause(e);
        } finally {
            StreamUtils.close(in, out, err);
            callback.onExit(0);
        }
    }

    public void destroy() {
	}

}
@@ -876,107 +876,9 @@
 .io.
-IOException;%0D%0Aimport java.io.InputStream;%0D%0Aimport java.io.OutputStream;%0D%0Aimport java.io.PrintStream
+*
 ;%0D%0Ai
@@ -1523,16 +1523,75 @@
 ession;%0D
+%0Aimport org.slf4j.Logger;%0D%0Aimport org.slf4j.LoggerFactory;%0D
 %0A%0D%0Apubli
@@ -1645,24 +1645,194 @@
 nAware %7B%0D%0A%0D%0A
+    public static final String SHELL_INIT_SCRIPT = %22karaf.shell.init.script%22;%0D%0A%0D%0A    private static final Logger LOGGER = LoggerFactory.getLogger(ShellCommand.class);%0D%0A%0D%0A
     private 
@@ -3020,24 +3020,153 @@
  %22root%22));%0D%0A
+            String scriptFileName = System.getProperty(SHELL_INIT_SCRIPT);%0D%0A            executeScript(scriptFileName, session);%0D%0A
             
@@ -4628,11 +4628,1006 @@
  %7B%0D%0A
-
 %09%7D%0D%0A%0D%0A
+    private void executeScript(String scriptFileName, CommandSession session) %7B%0D%0A        if (scriptFileName != null) %7B%0D%0A            Reader r = null;%0D%0A            try %7B%0D%0A                File scriptFile = new File(scriptFileName);%0D%0A                r = new InputStreamReader(new FileInputStream(scriptFile));%0D%0A                CharArrayWriter w = new CharArrayWriter();%0D%0A                int n;%0D%0A                char%5B%5D buf = new char%5B8192%5D;%0D%0A                while ((n = r.read(buf)) %3E 0) %7B%0D%0A                    w.write(buf, 0, n);%0D%0A                %7D%0D%0A                session.execute(new String(w.toCharArray()));%0D%0A            %7D catch (Exception e) %7B%0D%0A                LOGGER.debug(%22Error in initialization script%22, e);%0D%0A            %7D finally %7B%0D%0A                if (r != null) %7B%0D%0A                    try %7B%0D%0A                        r.close();%0D%0A                    %7D catch (IOException e) %7B%0D%0A                        // Ignore%0D%0A                    %7D%0D%0A                %7D%0D%0A            %7D%0D%0A        %7D%0D%0A    %7D%0D%0A%0D%0A
 %7D

Load command aliases (defined in shell.init.script) in the SSH ShellCommand