// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package socket.ssl.text;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.KeyStore;

import javax.net.ssl.KeyManagerFactory;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;

public class AsyncServer {
    public static enum NextPhase { WAIT_INTADD, WAIT_STRDUP, DONE }
    private static class ReadHandler extends ChannelInboundHandlerAdapter {
        private NextPhase state;
        public ReadHandler(Channel ch) {
            state = NextPhase.WAIT_INTADD;
        }
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws UnsupportedEncodingException, InterruptedException {
            String line;
            switch(state) {
                case WAIT_INTADD:
                    line = (String)msg;
                    // read a and b
                    String[] parts = line.split(" ");
                    int a = Integer.parseInt(parts[0]);
                    int b = Integer.parseInt(parts[1]);
                    // calculate c and send
                    int c = a + b;
                    ctx.channel().writeAndFlush(Integer.toString(c) + "\r\n");
                    // update state
                    state = NextPhase.WAIT_STRDUP;
                    break;
                case WAIT_STRDUP:
                    line = (String)msg;
                    // read v
                    String v = line;
                    // calculate v2 and send
                    String v2 = v + v;
                    ctx.channel().writeAndFlush(v2 + "\r\n");
                    // update state
                    state = NextPhase.DONE;
                    break;
                case DONE:
                    // ignore
                    break;
            }
        }
    }
    private static SslContext setupSSLContext(String keystore, String passphrase) throws Exception {
        KeyStore ks = KeyStore.getInstance("pkcs12");
        InputStream is = new FileInputStream(keystore);
        ks.load(is, passphrase.toCharArray());
        is.close();
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, passphrase.toCharArray());
        return SslContextBuilder.forServer(kmf).protocols("TLSv1.2").build();
    }
    private static final int PORT = 12345;
    private static final int BACKLOG = 100;
    public static void main(String[] args) throws Exception {
        // setup context
        SslContext sslctx = setupSSLContext("/work/sslserver.pfx", "topsecret");
        EventLoopGroup g = new NioEventLoopGroup(1);
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(g).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, BACKLOG);
            // define handler
            b.childHandler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 public void initChannel(SocketChannel ch) throws Exception {
                     System.out.printf("(connection from %s)\n", ch.remoteAddress());
                     ch.pipeline().addLast(sslctx.newHandler(ch.alloc()))
                                  .addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()))
                                  .addLast(new StringDecoder())
                                  .addLast(new StringEncoder())
                                  .addLast(new ReadHandler(ch));
                 }
             });
            // listen on port
            ChannelFuture f = b.bind(PORT).sync();
            // close connection when done (never)
            f.channel().closeFuture().sync();
        } finally {
            // teardown context
            g.shutdownGracefully();
        }       
    }
}
