/*
 * 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.console.impl.jline;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.URL;
import java.security.KeyPair;
import java.util.Hashtable;

import javax.security.auth.Subject;

import jline.Terminal;

import org.apache.felix.service.command.CommandProcessor;
import org.apache.karaf.jaas.boot.principal.UserPrincipal;
import org.apache.karaf.shell.console.Console;
import org.apache.karaf.shell.console.ConsoleFactory;
import org.apache.sshd.agent.SshAgent;
import org.apache.sshd.agent.local.AgentImpl;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LocalConsoleManager {

    private static final Logger LOGGER = LoggerFactory.getLogger(LocalConsoleManager.class);

    private ConsoleFactory consoleFactory;
    private BundleContext bundleContext;
    private TerminalFactory terminalFactory;
    private Console console;
    private boolean start;
    private final int defaultStartLevel;
    private CommandProcessor commandProcessor;
    private ServiceRegistration registration;
    private SshAgent local;

    public LocalConsoleManager(boolean start, 
            String defaultStartLevel,
            BundleContext bundleContext, 
            TerminalFactory terminalFactory, 
            ConsoleFactory consoleFactory,
            CommandProcessor commandProcessor) throws Exception {
        this.start = start;
        this.defaultStartLevel = Integer.parseInt(defaultStartLevel);
        this.bundleContext = bundleContext;
        this.terminalFactory = terminalFactory;
        this.consoleFactory = consoleFactory;
        this.commandProcessor = commandProcessor;
        start();
    }

    public void start() throws Exception {
        if (!start) {
            return;
        }
        final Subject subject = new Subject();
        subject.getPrincipals().add(new UserPrincipal("karaf"));

        final Terminal terminal = terminalFactory.getTerminal();
        Runnable callback = new Runnable() {
            public void run() {
                try {
                    bundleContext.getBundle(0).stop();
                } catch (Exception e) {
                    // Ignore
                }
            }
        };
        String agentId = startAgent("karaf");
        this.console = consoleFactory.createLocal(this.commandProcessor, terminal, callback);
        this.console.getSession().put(SshAgent.SSH_AUTHSOCKET_ENV_NAME, agentId);
        
        Runnable consoleStarter = new Runnable() {
            public void run() {
                consoleFactory.startConsoleAs(console, subject, "Local");
            }
        };
        
        boolean delayconsole = Boolean.parseBoolean(System.getProperty("karaf.delay.console"));
        if (delayconsole) {
            DelayedStarted watcher = new DelayedStarted(consoleStarter, bundleContext, System.in);
            new Thread(watcher).start();
        } else {
            consoleStarter.run();
        }
    }

    protected String startAgent(String user) {
        try {
            local = SshAgentLoader.load(bundleContext);
            String agentId = "local:" + user;
            Hashtable properties = new Hashtable();
            properties.put("id", agentId);
            registration = bundleContext.registerService(SshAgent.class.getName(), local, properties);
            return agentId;
        } catch (Throwable e) {
            LOGGER.warn("Error starting ssh agent for local console", e);
            return null;
        }
    }

    public void stop() throws Exception {
        if (registration != null) {
            registration.unregister();
        }
        // The bundle is stopped
        // so close the console and remove the callback so that the
        // osgi framework isn't stopped
        if (console != null) {
            console.close(false);
        }
    }

    static class SshAgentLoader {
        static SshAgent load(BundleContext bundleContext) {
            try {
                SshAgent agent = new AgentImpl();
                URL url = bundleContext.getBundle().getResource("karaf.key");
                InputStream is = url.openStream();
                ObjectInputStream r = new ObjectInputStream(is);
                KeyPair keyPair = (KeyPair) r.readObject();
                agent.addIdentity(keyPair, "karaf");
                return agent;
            } catch (Throwable e) {
                LOGGER.warn("Error starting ssh agent for local console", e);
                return null;
            }
        }
    }

}

@@ -936,16 +936,49 @@
 et.URL;%0A
+import java.nio.charset.Charset;%0A
 import j
@@ -999,16 +999,16 @@
 eyPair;%0A
-
 import j
@@ -1027,17 +1027,16 @@
 htable;%0A
-%0A
 import j
@@ -1064,16 +1064,16 @@
 bject;%0A%0A
+
 import j
@@ -1087,17 +1087,16 @@
 rminal;%0A
-%0A
 import o
@@ -3184,32 +3184,367 @@
 Agent(%22karaf%22);%0A
+        String ctype = System.getenv(%22LC_CTYPE%22);%0A        String encoding = ctype;%0A        if (encoding != null && encoding.indexOf('.') %3E 0) %7B%0A            encoding = encoding.substring(encoding.indexOf('.') + 1);%0A        %7D else %7B%0A            encoding = System.getProperty(%22input.encoding%22, Charset.defaultCharset().name());%0A        %7D%0A
         this.con
@@ -3609,16 +3609,26 @@
 erminal,
+ encoding,
  callbac

Fix forgotten conflict