/*
 * Copyright 2014 The gRPC Authors
 *
 * 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.
 */

package io.grpc.testing.integration;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Splitter;
import com.google.common.util.concurrent.MoreExecutors;
import io.grpc.InsecureServerCredentials;
import io.grpc.Server;
import io.grpc.ServerCredentials;
import io.grpc.ServerInterceptors;
import io.grpc.TlsServerCredentials;
import io.grpc.alts.AltsServerCredentials;
import io.grpc.internal.testing.TestUtils;
import io.grpc.netty.NettyServerBuilder;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/** Server that manages startup/shutdown of a single {@code TestService}. */
public class TestServiceServer {
  /** The main application allowing this server to be launched from the command line. */
  public static void main(String[] args) throws Exception {
    // Let Netty use Conscrypt if it is available.
    TestUtils.installConscryptIfAvailable();
    final TestServiceServer server = new TestServiceServer();
    server.parseArgs(args);
    if (server.useTls) {
      System.out.println(
          "\nUsing fake CA for TLS certificate. Test clients should expect host\n"
              + "*.test.google.fr and our test CA. For the Java test client binary, use:\n"
              + "--server_host_override=foo.test.google.fr --use_test_ca=true\n");
    }

    Runtime.getRuntime()
        .addShutdownHook(
            new Thread() {
              @Override
              @SuppressWarnings("CatchAndPrintStackTrace")
              public void run() {
                try {
                  System.out.println("Shutting down");
                  server.stop();
                } catch (Exception e) {
                  e.printStackTrace();
                }
              }
            });
    server.start();
    System.out.println("Server started on port " + server.port);
    server.blockUntilShutdown();
  }

  private final ArrayList<Integer> port = new ArrayList<>(Collections.singletonList(8080));
  private boolean useTls = true;
  private boolean useAlts = false;

  private ScheduledExecutorService executor;
  private Server server;

  @VisibleForTesting
  void parseArgs(String[] args) {
    boolean usage = false;
    for (String arg : args) {
      if (!arg.startsWith("--")) {
        System.err.println("All arguments must start with '--': " + arg);
        usage = true;
        break;
      }
      String[] parts = arg.substring(2).split("=", 2);
      String key = parts[0];
      if ("help".equals(key)) {
        usage = true;
        break;
      }
      if (parts.length != 2) {
        System.err.println("All arguments must be of the form --arg=value");
        usage = true;
        break;
      }
      String value = parts[1];
      if ("port".equals(key)) {
        port.clear();
        for (String v : Splitter.on(',').split(value)) {
          port.add(Integer.parseInt(v.trim()));
        }
        if (port.isEmpty()) {
          System.err.println("Unknown server port");
          usage = true;
          break;
        }
      } else if ("use_tls".equals(key)) {
        useTls = Boolean.parseBoolean(value);
      } else if ("use_alts".equals(key)) {
        useAlts = Boolean.parseBoolean(value);
      } else if ("grpc_version".equals(key)) {
        if (!"2".equals(value)) {
          System.err.println("Only grpc version 2 is supported");
          usage = true;
          break;
        }
      } else {
        System.err.println("Unknown argument: " + key);
        usage = true;
        break;
      }
    }
    if (useAlts) {
      useTls = false;
    }
    if (usage) {
      TestServiceServer s = new TestServiceServer();
      System.out.println(
          "Usage: [ARGS...]"
              + "\n"
              + "\n  --port=<port_1>,<port_2>...<port_N>  Port to connect to. Default " + s.port
              + "\n  --use_tls=true|false  Whether to use TLS. Default " + s.useTls
              + "\n  --use_alts=true|false Whether to use ALTS. Enable ALTS will disable TLS."
              + "\n                        Default " + s.useAlts
      );
      System.exit(1);
    }
  }

  @VisibleForTesting
  void start() throws Exception {
    executor = Executors.newSingleThreadScheduledExecutor();
    ServerCredentials serverCreds;
    if (useAlts) {
      serverCreds = AltsServerCredentials.create();
    } else if (useTls) {
      serverCreds = TlsServerCredentials.create(
          TestUtils.loadCert("server1.pem"), TestUtils.loadCert("server1.key"));
    } else {
      serverCreds = InsecureServerCredentials.create();
    }
    NettyServerBuilder serverBuilder = NettyServerBuilder.forPort(port.get(0), serverCreds);
    for (int i = 1; i < port.size(); i++) {
      serverBuilder.addListenAddress(new InetSocketAddress(port.get(i)));
    }
    server = serverBuilder.maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE)
        .addService(
            ServerInterceptors.intercept(
                new TestServiceImpl(executor), TestServiceImpl.interceptors()))
        .build()
        .start();
  }

  @VisibleForTesting
  void stop() throws Exception {
    server.shutdownNow();
    if (!server.awaitTermination(5, TimeUnit.SECONDS)) {
      System.err.println("Timed out waiting for server shutdown");
    }
    MoreExecutors.shutdownAndAwaitTermination(executor, 5, TimeUnit.SECONDS);
  }

  @VisibleForTesting
  int getPort() {
    return server.getPort();
  }

  /** Await termination on the main thread since the grpc library uses daemon threads. */
  private void blockUntilShutdown() throws InterruptedException {
    if (server != null) {
      server.awaitTermination();
    }
  }
}

@@ -692,48 +692,8 @@
 ng;%0A
-import com.google.common.base.Splitter;%0A
 impo
@@ -740,24 +740,45 @@
 eExecutors;%0A
+import io.grpc.Grpc;%0A
 import io.gr
@@ -1026,142 +1026,8 @@
 ls;%0A
-import io.grpc.netty.NettyServerBuilder;%0Aimport java.net.InetSocketAddress;%0Aimport java.util.ArrayList;%0Aimport java.util.Collections;%0A
 impo
@@ -2486,88 +2486,23 @@
 ate 
-f
 in
-al ArrayList%3CInteger%3E port = new ArrayList%3C%3E(Collections.singletonList(
+t port = 
 8080
-))
 ;%0A  
@@ -3298,266 +3298,35 @@
 port
-.clear();%0A        for (String v : Splitter.on(',').split(value)) %7B%0A          port.add(Integer.parseInt(v.trim()));%0A        %7D%0A        if (port.isEmpty()) %7B%0A          System.err.println(%22Unknown server port%22);%0A          usage = true;%0A          break;%0A        %7D
+ = Integer.parseInt(value);
 %0A   
@@ -4045,36 +4045,21 @@
 ort=
-%3Cport_1%3E,%3Cport_2%3E...%3Cport_N%3E
+PORT         
   Po
@@ -4841,48 +4841,25 @@
     
-NettyServerBuilder serverBuilder = Netty
+server = Grpc.new
 Serv
@@ -4867,18 +4867,17 @@
 rBuilder
-.f
+F
 orPort(p
@@ -4883,15 +4883,8 @@
 port
-.get(0)
 , se
@@ -4897,160 +4897,17 @@
 eds)
-;
 %0A    
-for (int i = 1; i %3C port.size(); i++) %7B%0A      serverBuilder.addListenAddress(new InetSocketAddress(port.get(i)));%0A    %7D%0A    server = serverBuilder
+    
 .max

Revert "interop-testing: allow multiple port in test server (#7799)" (#7805)