package artifacts;

import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;

public class MavenArtifactInstaller {

  public static final String MVN_INSTALL_PATH =
      "F:\\local_work\\program\\apache-maven-3.5.2-bin\\bin\\";
  public static final String CONFIG = "/settings.xml";
  public static final String REPO_SCAN_PATH = "/repository/iaik/prod";

  public static final String GROUP = "iaik.prod";
  public static final String PACKAGE = "jar";
  public static final String COMMAND_TEMPLATE =
      "{6}mvn.cmd install:install-file -s {0} -DgroupId={1} -DartifactId={2} -Dversion={3} -Dpackaging={4} -Dfile={5}";

  /**
   * Only for test-deployment of maven artifacts.
   *
   * @param args System parameters
   */
  public static void main(final String[] args) {
    String currentLocation = new java.io.File(".").toURI().toString();
    currentLocation = currentLocation.substring("file:/".length(), currentLocation.length() - 2);
    final String settingLocation = currentLocation + CONFIG;
    final File settingsFile = new File(settingLocation);
    if (!settingsFile.exists()) {
      System.out.println("Maven settings does not exist");
      System.exit(-1);

    }

    final String pathToScan = currentLocation + REPO_SCAN_PATH;

    final File toScan = new File(pathToScan);

    int counter = 0;
    for (final File dir : toScan.listFiles()) {
      final String artifactName = dir.getName();
      for (final File version : dir.listFiles()) {
        final String libVersion = version.getName();
        final String jarPath =
            version.getAbsolutePath() + "/" + artifactName + "-" + libVersion + ".jar";
        final File jar = new File(jarPath);
        if (jar.exists()) {
          final String mvnCommand =
              MessageFormat.format(COMMAND_TEMPLATE, settingsFile.getAbsoluteFile(), GROUP,
                  artifactName, libVersion, PACKAGE, jar.getAbsolutePath(), MVN_INSTALL_PATH);
          System.out.println("Execute: " + mvnCommand);
          try {
            Runtime.getRuntime().exec(mvnCommand);
            counter++;
          } catch (final IOException e) {
            e.printStackTrace();

          }

        } else {
          System.out.print("Can NOT find jar with path: " + jarPath);
        }

      }

    }
    System.out.println("Install #" + counter + " maven artifacts");
  }

}