/**
   * Adds users to the Zookeeper registry.
   *
   * @param zookeeper
   * @param users
   * @throws KeeperException
   * @throws InterruptedException
   */
  private void addUsersToZookeeper(IZKClient zookeeper, Map<String, String> users)
      throws KeeperException, InterruptedException, TimeoutException {
    Pattern p = Pattern.compile("(.+),(.+)");
    Map<String, Object> options = new HashMap<String, Object>();
    options.put("encryption.prefix", "{CRYPT}");
    options.put("encryption.suffix", "{CRYPT}");
    options.put("encryption.enabled", "true");
    options.put("encryption.enabled", "true");
    options.put("encryption.algorithm", "MD5");
    options.put("encryption.encoding", "hexadecimal");
    options.put(BundleContext.class.getName(), bundleContext);
    EncryptionSupport encryptionSupport = new EncryptionSupport(options);
    Encryption encryption = encryptionSupport.getEncryption();

    StringBuilder sb = new StringBuilder();

    for (Map.Entry<String, String> entry : users.entrySet()) {
      String user = entry.getKey();
      Matcher m = p.matcher(entry.getValue());
      if (m.matches() && m.groupCount() >= 2) {
        String password = m.group(1).trim();
        if (!password.startsWith(encryptionSupport.getEncryptionPrefix())
            || !password.endsWith(encryptionSupport.getEncryptionSuffix())) {
          password =
              encryptionSupport.getEncryptionPrefix()
                  + encryption.encryptPassword(m.group(1)).trim()
                  + encryptionSupport.getEncryptionSuffix();
        }
        String role = m.group(2).trim();
        sb.append(user).append("=").append(password).append(",").append(role).append("\n");
      }
    }
    String allUsers = sb.toString();
    ZooKeeperRetriableUtils.createDefault(zookeeper, "/fabric/authentication/users", allUsers);
  }
  public void createLocalServer(int port, CreateEnsembleOptions options) {
    try {
      IZKClient client;
      Hashtable<String, Object> properties;
      String version = ZkDefs.DEFAULT_VERSION;
      String karafName = System.getProperty(SystemProperties.KARAF_NAME);
      String minimumPort = System.getProperty(ZkDefs.MINIMUM_PORT);
      String maximumPort = System.getProperty(ZkDefs.MAXIMUM_PORT);
      int mappedPort = mapPortToRange(port, minimumPort, maximumPort);

      if (options.getZookeeperPassword() != null) {
        // do nothing
      } else if (System.getProperties().containsKey(SystemProperties.ZOOKEEPER_PASSWORD)) {
        options.setZookeeperPassword(System.getProperty(SystemProperties.ZOOKEEPER_PASSWORD));
      } else {
        options.setZookeeperPassword(ZooKeeperRetriableUtils.generatePassword());
      }

      // Install or stop the fabric-configadmin bridge
      Bundle bundleFabricAgent =
          findAndStopBundle(bundleContext, "org.fusesource.fabric.fabric-agent");
      Bundle bundleFabricConfigAdmin =
          installOrStopBundle(
              bundleContext,
              "org.fusesource.fabric.fabric-configadmin",
              "mvn:org.fusesource.fabric/fabric-configadmin/" + FabricConstants.FABRIC_VERSION);
      Bundle bundleFabricZooKeeper =
          installOrStopBundle(
              bundleContext,
              "org.fusesource.fabric.fabric-zookeeper",
              "mvn:org.fusesource.fabric/fabric-zookeeper/" + FabricConstants.FABRIC_VERSION);
      Bundle bundleFabricJaas =
          installOrStopBundle(
              bundleContext,
              "org.fusesource.fabric.fabric-jaas  ",
              "mvn:org.fusesource.fabric/fabric-jaas/" + FabricConstants.FABRIC_VERSION);
      Bundle bundleFabricCommands =
          installOrStopBundle(
              bundleContext,
              "org.fusesource.fabric.fabric-commands  ",
              "mvn:org.fusesource.fabric/fabric-commands/" + FabricConstants.FABRIC_VERSION);
      Bundle bundleFabricMavenProxy =
          installOrStopBundle(
              bundleContext,
              "org.fusesource.fabric.fabric-commands  ",
              "mvn:org.fusesource.fabric/fabric-maven-proxy/" + FabricConstants.FABRIC_VERSION);

      // Create configuration
      String connectionUrl = HostUtils.getLocalHostName() + ":" + Integer.toString(mappedPort);

      String autoImportFrom = System.getProperty(SystemProperties.PROFILES_AUTOIMPORT_PATH);

      Configuration config =
          configurationAdmin.createFactoryConfiguration("org.fusesource.fabric.zookeeper.server");
      properties = new Hashtable<String, Object>();
      if (autoImportFrom != null) {
        loadPropertiesFrom(
            properties,
            autoImportFrom
                + "/fabric/configs/versions/1.0/profiles/default/org.fusesource.fabric.zookeeper.server.properties");
      }
      properties.put("tickTime", "2000");
      properties.put("initLimit", "10");
      properties.put("syncLimit", "5");
      properties.put("dataDir", "data/zookeeper/0000");
      properties.put("clientPort", Integer.toString(mappedPort));
      properties.put("fabric.zookeeper.pid", "org.fusesource.fabric.zookeeper.server-0000");
      config.setBundleLocation(null);
      config.update(properties);

      // Update the client configuration
      config = configurationAdmin.getConfiguration("org.fusesource.fabric.zookeeper");
      properties = new Hashtable<String, Object>();
      if (autoImportFrom != null) {
        loadPropertiesFrom(
            properties,
            autoImportFrom
                + "/fabric/configs/versions/1.0/profiles/default/org.fusesource.fabric.zookeeper.properties");
      }
      properties.put("zookeeper.url", connectionUrl);
      properties.put(
          "zookeeper.timeout",
          System.getProperties().containsKey("zookeeper.timeout")
              ? System.getProperties().getProperty("zookeeper.timeout")
              : "30000");
      properties.put("fabric.zookeeper.pid", "org.fusesource.fabric.zookeeper");
      properties.put("zookeeper.password", options.getZookeeperPassword());
      config.setBundleLocation(null);
      config.update(properties);

      // Start fabric-zookeeper bundle
      bundleFabricZooKeeper.start();

      // Wait for the client to be available
      ServiceTracker tracker = new ServiceTracker(bundleContext, IZKClient.class.getName(), null);
      tracker.open();
      client = (IZKClient) tracker.waitForService(5000);
      if (client == null) {
        throw new IllegalStateException("Timeout waiting for ZooKeeper client to be registered");
      }
      tracker.close();
      client.waitForConnected();

      // Import data into zookeeper
      if (autoImportFrom != null) {
        getDataStore().importFromFileSystem(autoImportFrom);
      }

      getDataStore().setDefaultVersion(version);

      // configure default profile
      String defaultProfile = getDataStore().getProfile(version, "default", true);

      ZooKeeperRetriableUtils.set(
          client,
          ZkPath.CONFIG_ENSEMBLE_URL.getPath(),
          "${zk:" + karafName + "/ip}:" + Integer.toString(mappedPort));
      ZooKeeperRetriableUtils.set(
          client, ZkPath.CONFIG_ENSEMBLE_PASSWORD.getPath(), options.getZookeeperPassword());

      Properties zkProps = new Properties();
      zkProps.setProperty("zookeeper.url", "${zk:" + ZkPath.CONFIG_ENSEMBLE_URL.getPath() + "}");
      zkProps.setProperty(
          "zookeeper.password", "${zk:" + ZkPath.CONFIG_ENSEMBLE_PASSWORD.getPath() + "}");
      getDataStore()
          .setFileConfiguration(
              version,
              defaultProfile,
              "org.fusesource.fabric.zookeeper.properties",
              DataStoreHelpers.toBytes(zkProps));

      // configure the ensemble
      String ensembleProfile = getDataStore().getProfile(version, "fabric-ensemble-0000", true);
      getDataStore().setProfileAttribute(version, ensembleProfile, "abstract", "true");
      getDataStore().setProfileAttribute(version, ensembleProfile, "hidden", "true");

      Properties ensembleProps = new Properties();
      ensembleProps.put("tickTime", "2000");
      ensembleProps.put("initLimit", "10");
      ensembleProps.put("syncLimit", "5");
      ensembleProps.put("dataDir", "data/zookeeper/0000");

      loadPropertiesFrom(
          ensembleProps,
          autoImportFrom
              + "/fabric/configs/versions/1.0/profiles/default/org.fusesource.fabric.zookeeper.server.properties");
      getDataStore()
          .setFileConfiguration(
              version,
              ensembleProfile,
              "org.fusesource.fabric.zookeeper.server-0000.properties",
              DataStoreHelpers.toBytes(ensembleProps));

      // configure this server in the ensemble
      String ensembleServerProfile =
          getDataStore().getProfile(version, "fabric-ensemble-0000-1", true);
      getDataStore().setProfileAttribute(version, ensembleServerProfile, "hidden", "true");
      getDataStore()
          .setProfileAttribute(version, ensembleServerProfile, "parents", ensembleProfile);
      Properties serverProps = new Properties();
      serverProps.put("clientPort", String.valueOf(mappedPort));
      getDataStore()
          .setFileConfiguration(
              version,
              ensembleServerProfile,
              "org.fusesource.fabric.zookeeper.server-0000.properties",
              DataStoreHelpers.toBytes(serverProps));

      ZooKeeperRetriableUtils.set(client, ZkPath.CONFIG_ENSEMBLES.getPath(), "0000");
      ZooKeeperRetriableUtils.set(client, ZkPath.CONFIG_ENSEMBLE.getPath("0000"), karafName);

      // configure fabric profile
      String fabricProfile = getDataStore().getProfile(version, "fabric", true);
      Properties agentProps =
          DataStoreHelpers.toProperties(
              getDataStore()
                  .getFileConfiguration(
                      version, fabricProfile, "org.fusesource.fabric.agent.properties"));
      agentProps.put("feature.fabric-commands", "fabric-commands");
      getDataStore()
          .setFileConfiguration(
              version,
              "fabric",
              "org.fusesource.fabric.agent.properties",
              DataStoreHelpers.toBytes(agentProps));

      ZooKeeperRetriableUtils.createDefault(
          client, ZkPath.CONFIG_CONTAINER.getPath(karafName), version);
      String assignedProfile = System.getProperty(SystemProperties.PROFILE);
      if (assignedProfile != null
          && !assignedProfile.isEmpty()
          && !"fabric".equals(assignedProfile)) {
        ZooKeeperRetriableUtils.createDefault(
            client,
            ZkPath.CONFIG_VERSIONS_CONTAINER.getPath(version, karafName),
            "fabric fabric-ensemble-0000-1 " + assignedProfile);
      } else {
        ZooKeeperRetriableUtils.createDefault(
            client,
            ZkPath.CONFIG_VERSIONS_CONTAINER.getPath(version, karafName),
            "fabric fabric-ensemble-0000-1");
      }

      // add auth
      Map<String, String> configs = new HashMap<String, String>();
      configs.put("encryption.enabled", "${zk:/fabric/authentication/encryption.enabled}");
      getDataStore()
          .setConfiguration(version, defaultProfile, "org.fusesource.fabric.jaas", configs);

      // outside of the profile storage area, so we'll keep these in zk
      ZooKeeperRetriableUtils.createDefault(
          client, "/fabric/authentication/encryption.enabled", "true");
      ZooKeeperRetriableUtils.createDefault(client, "/fabric/authentication/domain", "karaf");
      addUsersToZookeeper(client, options.getUsers());

      ZooKeeperRetriableUtils.createDefault(
          client, ZkPath.AUTHENTICATION_CRYPT_ALGORITHM.getPath(), "PBEWithMD5AndDES");
      ZooKeeperRetriableUtils.createDefault(
          client, ZkPath.AUTHENTICATION_CRYPT_PASSWORD.getPath(), options.getZookeeperPassword());

      // Fix acls
      ZookeeperCommandBuilder.fixAcls("/", true).execute(client);

      // Reset the autostart flag
      if (ensembleAutoStart) {
        System.setProperty(SystemProperties.ENSEMBLE_AUTOSTART, Boolean.FALSE.toString());
        File file = new File(System.getProperty("karaf.base") + "/etc/system.properties");
        org.apache.felix.utils.properties.Properties props =
            new org.apache.felix.utils.properties.Properties(file);
        props.put(SystemProperties.ENSEMBLE_AUTOSTART, Boolean.FALSE.toString());
        props.save();
      }

      // Restart fabric-configadmin bridge
      bundleFabricConfigAdmin.start();
      bundleFabricJaas.start();
      bundleFabricCommands.start();
      bundleFabricMavenProxy.start();

      // Check if the agent is configured to auto start.
      if (!System.getProperties().containsKey(SystemProperties.AGENT_AUTOSTART)
          || Boolean.parseBoolean(System.getProperty(SystemProperties.AGENT_AUTOSTART))) {
        bundleFabricAgent =
            findOrInstallBundle(
                bundleContext,
                "org.fusesource.fabric.fabric-agent  ",
                "mvn:org.fusesource.fabric/fabric-agent/" + FabricConstants.FABRIC_VERSION);
        bundleFabricAgent.start();
      }
    } catch (Exception e) {
      throw new FabricException("Unable to create zookeeper server configuration", e);
    }
  }