package org.opencb.opencga.app.cli.admin.executors;

import org.opencb.opencga.app.cli.admin.executors.migration.NewVariantMetadataMigration;
import org.opencb.opencga.app.cli.admin.options.MigrationCommandOptions;
import org.opencb.opencga.catalog.auth.authentication.CatalogAuthenticationManager;
import org.opencb.opencga.catalog.db.mongodb.MongoDBAdaptorFactory;
import org.opencb.opencga.catalog.managers.CatalogManager;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.nio.file.Paths;

/**
 * Created on 08/09/17.
 *
 * @author Jacobo Coll &lt;jacobo167@gmail.com&gt;
 */
public class MigrationCommandExecutor extends AdminCommandExecutor {

    private final MigrationCommandOptions migrationCommandOptions;

    public MigrationCommandExecutor(MigrationCommandOptions migrationCommandOptions) {
        super(migrationCommandOptions.getCommonOptions());
        this.migrationCommandOptions = migrationCommandOptions;
    }

    @Override
    public void execute() throws Exception {
        logger.debug("Executing migration command line");

        String subCommandString = migrationCommandOptions.getSubCommand();
        switch (subCommandString) {
//            case "latest":
            case "v1.3.0":
                v1_3_0();
                break;
            default:
                logger.error("Subcommand '{}' not valid", subCommandString);
                break;
        }
    }

    private void v1_3_0() throws Exception {
        logger.info("MIGRATING v1.3.0");
        MigrationCommandOptions.MigrateV1_3_0CommandOptions options = migrationCommandOptions.getMigrateV130CommandOptions();

        if (options.files != null && !options.files.isEmpty()) {
            // Just migrate files. Do not even connect to Catalog!
            NewVariantMetadataMigration migration = new NewVariantMetadataMigration(storageConfiguration, null, options);
            for (String file : options.files) {
                migration.migrateVariantFileMetadataFile(Paths.get(file));
            }
        } else {
            setCatalogDatabaseCredentials(options, options.commonOptions);

            try (CatalogManager catalogManager = new CatalogManager(configuration)) {
                String sessionId = catalogManager.getUserManager().login("admin", options.commonOptions.adminPassword);

                // Catalog
                String line;
                String basePath = appHome + "/migration/v1.3.0/";
                String catalogCli = "mongo " + configuration.getCatalog().getDatabase().getHosts().get(0) + "/"
                        + catalogManager.getCatalogDatabase() + " opencga_catalog_v1.2.x_to_1.3.0.js";

                logger.info("Migrating Catalog. Running {} from {}", catalogCli, basePath);
                ProcessBuilder processBuilder = new ProcessBuilder(catalogCli.split(" "));
                processBuilder.directory(new File(basePath));
                Process p = processBuilder.start();

                BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
                while ((line = input.readLine()) != null) {
                    logger.info(line);
                }
                input.close();


                // Storage

                new NewVariantMetadataMigration(storageConfiguration, catalogManager, options).migrate(sessionId);
            }
        }
    }

}

@@ -46,16 +46,61 @@
 utors;%0A%0A
+import org.apache.commons.lang3.StringUtils;%0A
 import o
@@ -2447,20 +2447,102 @@
  String 
-line
+basePath = appHome + %22/migration/v1.3.0/%22;%0A%0A                String authentication = %22%22
 ;%0A      
@@ -2555,57 +2555,568 @@
     
+if (
 String
- basePath = appHome + %22/m
+Utils.isNotEmpty(configuration.getCatalog().getDatabase().getUser())%0A                        && StringUtils.isNotEmpty(configuration.getCatalog().getDatabase().getPassword())) %7B%0A                    authentication = %22-u %22 + configuration.getCatalog().getDatabase().getUser() + %22 -p %22%0A                            + configuration.getCatalog().getDatabase().getPassword() + %22 --authenticationDatabase %22%0A                            + conf
 ig
+u
 ration
-/v1.3.0/%22;
+.getCatalog().getDatabase().getOptions().getOrDefault(%22authenticationDatabase%22, %22admin%22);%0A                %7D%0A
 %0A   
@@ -3154,24 +3154,41 @@
 = %22mongo %22 +
+ authentication +
  configurati
@@ -3639,24 +3639,24 @@
 r.start();%0A%0A
-
             
@@ -3741,24 +3741,53 @@
 Stream()));%0A
+                String line;%0A
             

add user and password authentication to catalog migration