package org.apache.maven.deploy.deployers;

/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Apache" and "Apache Software Foundation" and
 *    "Apache MavenSession" must not be used to endorse or promote products
 *    derived from this software without prior written permission. For
 *    written permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    "Apache MavenSession", nor may "Apache" appear in their name, without
 *    prior written permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 * ====================================================================
 */

import java.io.File;

import org.apache.maven.deploy.RepositoryInfo;
import org.apache.maven.deploy.exceptions.AuthenticationException;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Proxy;
import com.jcraft.jsch.ProxyHTTP;
import com.jcraft.jsch.ProxySOCKS5;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;

/**
 * A base class for deployers using  protocols from SSH2 family  
 * and JSch library for underlining implmenetation 
 * 
 * This is responsible for authentification stage of the process.
 * 
 * We will first try to
 * use public keys for authentication 
 * and if that doesn't work then we fall back
 * to using the login and password
 * 
 * @version $Id: GenericSshDeployer.java,v 1.7 2003/08/19 04:45:05 dion Exp $
 * @todo still have to account for differing setups for people deploying to
 *      their own sites and to the central repository.
 * @todo improve exception handling
 */
public abstract class GenericSshDeployer extends AbstractDeployer
{

    private RepositoryInfo repoInfo;

    /** Default port used for SSH protocol */
    public final static int DEFAULT_SSH_PORT = 22;

    /** Default port used by SOCKS5 proxy server */
    public final static int SOCKS5_PROXY_PORT = 1080;

    private Session session = null;

    /**
     * @return
     */
    public Session getSession()
    {
        return session;
    }

    /* (non-Javadoc)
     * @see org.apache.maven.deploy.deployers.Deployer#getAuthenticationInfo()
     */
    public RepositoryInfo getRepositoryInfo()
    {
        return repoInfo;
    }

    /**
     * @see org.apache.maven.deploy.deployers.Deployer#release()
     */
    public void release()
    {
        session.disconnect();
    }

    /* (non-Javadoc)
     * @see org.apache.maven.deploy.deployers.Deployer#init(org.apache.maven.deploy.HostInfo)
     */
    public void init(RepositoryInfo repoInfo)
        throws AuthenticationException
    {

        try
        {
            this.repoInfo = repoInfo;
            JSch jsch = new JSch();

            int port = repoInfo.getPort();
            if (port == RepositoryInfo.UNKNOWN_PORT)
            {
                port = DEFAULT_SSH_PORT;
            }
            System.out.println("host: '" + repoInfo.getHost() + "'");
            String host = repoInfo.getHost();
            session =
                jsch.getSession(repoInfo.getUserName(), host, port);

            // Look for the private key and use it if available.
            if (repoInfo.getPrivateKey() != null)
            {
                File privateKey = new File(repoInfo.getPrivateKey());

                if (privateKey.exists())
                {
                    if (repoInfo.getPassphrase() == null)
                    {
                        String msg =
                            "Private key provided "
                                + "without passphrase for repo: "
                                + repoInfo.getRepositoryAlias();
                        throw new AuthenticationException(msg);
                    }

                    System.out.println("Using private key: " + privateKey);
                    jsch.addIdentity(
                        privateKey.getAbsolutePath(),
                        repoInfo.getPassphrase());
                }
                else
                {
                    String msg = "Private key: " + privateKey + " not found ";
                    throw new AuthenticationException(msg);
                }
            }

            String proxyHost = repoInfo.getProxyHost();

            if (proxyHost != null)
            {
                Proxy proxy = null;
                int proxyPort = repoInfo.getProxyPort();
                // HACK:
                //if port == 1080 we will use SOCKS5 Proxy
                // otherwise will use HTTP Proxy

                if (proxyPort == SOCKS5_PROXY_PORT)
                {
                    proxy = new ProxySOCKS5(proxyHost);
                    ((ProxySOCKS5) proxy).setUserPasswd(
                        repoInfo.getProxyUserName(),
                        repoInfo.getProxyPassword());
                }
                else
                {
                    proxy = new ProxyHTTP(proxyHost, proxyPort);
                    ((ProxyHTTP) proxy).setUserPasswd(
                        repoInfo.getProxyUserName(),
                        repoInfo.getProxyPassword());
                }
                proxy.connect(session, host, port);

            }
            // username and password will be given via UserInfo interface.
            UserInfo ui = new MavenUserInfo(repoInfo);
            session.setUserInfo(ui);
            session.connect();

        }
        catch (Exception e)
        {
            e.printStackTrace();
            throw new AuthenticationException(
                "Cannot connect. Reason: " + e.getMessage(),
                e);
        }
    }

    /**
     * MavenUserInfo class which returns the necessary name and password from
     * the POM to secure an ssh connection.
     */
    public class MavenUserInfo implements UserInfo
    {

        RepositoryInfo repoInfo;

        MavenUserInfo(RepositoryInfo repoInfo)
        {
            this.repoInfo = repoInfo;
        }

        public String getPassphrase()
        {
            return repoInfo.getPassphrase();
        }

        /* (non-Javadoc)
         * @see com.jcraft.jsch.UserInfo#getPassword()
         */
        public String getPassword()
        {
            return repoInfo.getPassword();
        }

        /* (non-Javadoc)
         * @see com.jcraft.jsch.UserInfo#promptPassphrase(java.lang.String)
         */
        public boolean promptPassphrase(String arg0)
        {
            return true;
        }

        /* (non-Javadoc)
         * @see com.jcraft.jsch.UserInfo#promptPassword(java.lang.String)
         */
        public boolean promptPassword(String arg0)
        {
            return true;
        }

        /**
         * @see com.jcraft.jsch.UserInfo#promptYesNo(java.lang.String)
         */
        public boolean promptYesNo(String arg0)
        {
            return true;
        }

        /* (non-Javadoc)
         * @see com.jcraft.jsch.UserInfo#showMessage(java.lang.String)
         */
        public void showMessage(String message)
        {
            System.out.println(message);

        }

    }

}
