/*
 * Copyright Terracotta, Inc.
 *
 * 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 org.terracotta.management.integration.tests;

import org.terracotta.ipceventbus.proc.AnyProcess;
import org.terracotta.ipceventbus.proc.AnyProcessBuilder;
import org.terracotta.testing.config.DefaultStartupCommandBuilder;
import org.terracotta.testing.config.StartupCommandBuilder;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

import static org.terracotta.testing.config.ConfigConstants.DEFAULT_CLUSTER_NAME;
import static org.terracotta.testing.demos.TestHelpers.isWindows;

public class DynamicConfigStartupBuilder extends DefaultStartupCommandBuilder {
  private int stripeId;
  private String[] builtCommand;
  private int debugPort = Integer.getInteger("serverDebugPortStart", 0);

  @Override
  public StartupCommandBuilder stripeName(String stripeName) {
    this.stripeId = Integer.parseInt(stripeName.substring(6));
    return this;
  }

  @Override
  public String[] build() {
    if (builtCommand == null) {
      try {
        installServer();
        Path basePath = getKitDir().resolve("server").resolve("bin").resolve("start-tc-server");
        String startScript = isWindows() ? basePath + ".bat" : basePath + ".sh";
        if (isConsistentStartup()) {
          throw new UnsupportedOperationException("Consistent startup is not supported with start-node script");
        } else {
          Path generatedRepositories = convertConfigFiles();
          // moves the generated files onto the server folder, but only for this server we are building
          Files.move(generatedRepositories.resolve("stripe-" + stripeId).resolve(getServerName()), getServerWorkingDir().resolve("repository"));
          builtCommand = new String[]{startScript, "-r", "repository"};
        }
      } catch (IOException e) {
        throw new UncheckedIOException(e);
      }
    }

    return builtCommand;
  }

  private Path convertConfigFiles() {
    Path generatedRepositories = getServerWorkingDir().getParent().getParent().resolve("generated-repositories");

    if (Files.exists(generatedRepositories)) {
      // this builder is called fro each server, but the CLI will generate the repositories for all.
      return generatedRepositories;
    }

    List<String> command = new ArrayList<>();
    String script = getKitDir().resolve("tools").resolve("config-convertor").resolve("bin").resolve("config-convertor") + (isWindows() ? ".bat" : ".sh");
    command.add(script);
    command.add("convert");

    command.add("-c");
    command.add(getTcConfig().toString());

    command.add("-n");
    command.add(DEFAULT_CLUSTER_NAME);

    command.add("-d");
    command.add(getServerWorkingDir().relativize(generatedRepositories).toString());

    command.add("-f"); //Do not fail for relative paths

    AnyProcess process;
    try {
      AnyProcessBuilder<? extends AnyProcess> builder = AnyProcess.newBuilder()
          .command(command.toArray(new String[0]))
          .workingDir(getServerWorkingDir().toFile())
          .pipeStdout(System.out)
          .pipeStderr(System.err);
      if (debugPort > 0) {
        builder.env("JAVA_OPTS", "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=" + debugPort);
      }
      process = builder.build();
    } catch (Exception e) {
      throw new IllegalStateException("Error launching command: " + String.join(" ", command), e);
    }
    int exitStatus;
    try {
      exitStatus = process.waitFor();
    } catch (InterruptedException e) {
      throw new IllegalStateException(e);
    }
    if (exitStatus != 0) {
      throw new IllegalStateException("Process: " + process.getCommand() + " exited with status: " + exitStatus);
    }
    return generatedRepositories;
  }
}

@@ -1684,355 +1684,8 @@
 ();%0A
-        Path basePath = getKitDir().resolve(%22server%22).resolve(%22bin%22).resolve(%22start-tc-server%22);%0A        String startScript = isWindows() ? basePath + %22.bat%22 : basePath + %22.sh%22;%0A        if (isConsistentStartup()) %7B%0A          throw new UnsupportedOperationException(%22Consistent startup is not supported with start-node script%22);%0A        %7D else %7B%0A  
     
@@ -1735,26 +1735,24 @@
 figFiles();%0A
-  
         // m
@@ -1841,18 +1841,16 @@
 uilding%0A
-  
         
@@ -1996,81 +1996,30 @@
     
-  
 buil
-tCommand = new String%5B%5D%7BstartScript, %22-r%22, %22repository%22%7D;%0A        %7D
+dStartupCommand();
 %0A   
@@ -2100,25 +2100,24 @@
     %7D%0A    %7D%0A
-%0A
     return b
@@ -2123,24 +2123,483 @@
 builtCommand
+;%0A  %7D%0A%0A  private void buildStartupCommand() %7B%0A    List%3CString%3E command = new ArrayList%3C%3E();%0A    Path basePath = getKitDir().resolve(%22server%22).resolve(%22bin%22).resolve(%22start-tc-server%22);%0A    String startScript = isWindows() ? basePath + %22.bat%22 : basePath + %22.sh%22;%0A    command.add(startScript);%0A    if (isConsistentStartup()) %7B%0A      command.add(%22-c%22);%0A    %7D%0A    command.add(%22-r%22);%0A    command.add(%22repository%22);%0A    builtCommand = command.toArray(new String%5B0%5D)
 ;%0A  %7D%0A%0A  pri

Add support for consistent startup in DynamicConfigStartupBuilder