/*
 * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
 * agreements. See the NOTICE file distributed with this work for additional information regarding
 * copyright ownership. The ASF licenses this file to You 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.apache.geode.cache.lucene;

import static org.apache.geode.test.awaitility.GeodeAwaitility.await;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import org.junit.Test;

import org.apache.geode.cache.RegionShortcut;
import org.apache.geode.distributed.internal.InternalLocator;
import org.apache.geode.internal.AvailablePortHelper;
import org.apache.geode.test.dunit.AsyncInvocation;
import org.apache.geode.test.dunit.DistributedTestUtils;
import org.apache.geode.test.dunit.Host;
import org.apache.geode.test.dunit.NetworkUtils;
import org.apache.geode.test.dunit.VM;

public class RollingUpgradeReindexShouldBeSuccessfulWhenAllServersRollToCurrentVersion
    extends LuceneSearchWithRollingUpgradeDUnit {

  @Test
  public void luceneReindexShouldBeSuccessfulWhenAllServersRollToCurrentVersion() throws Exception {
    final Host host = Host.getHost(0);
    VM locator1 = host.getVM(oldVersion, 0);
    VM server1 = host.getVM(oldVersion, 1);
    VM server2 = host.getVM(oldVersion, 2);

    final String regionName = "aRegion";
    RegionShortcut shortcut = RegionShortcut.PARTITION_REDUNDANT;

    int locatorPort = AvailablePortHelper.getRandomAvailableTCPPort();
    locator1.invoke(() -> DistributedTestUtils.deleteLocatorStateFile(locatorPort));

    String hostName = NetworkUtils.getServerHostName(host);
    String locatorString = getLocatorString(locatorPort);
    String regionType = "partitionedRedundant";
    try {
      locator1.invoke(
          invokeStartLocator(hostName, locatorPort, getLocatorPropertiesPre91(locatorString)));
      invokeRunnableInVMs(invokeCreateCache(getSystemProperties(new int[] {locatorPort})), server1,
          server2);

      // Locators before 1.4 handled configuration asynchronously.
      // We must wait for configuration configuration to be ready, or confirm that it is disabled.
      locator1.invoke(
          () -> await()
              .untilAsserted(() -> assertTrue(
                  !InternalLocator.getLocator().getConfig().getEnableClusterConfiguration()
                      || InternalLocator.getLocator().isSharedConfigurationRunning())));

      locator1 =
          rollLocatorToCurrent(locator1, hostName, locatorPort, getTestMethodName(), locatorString);

      server1 = rollServerToCurrentAndCreateRegionOnly(server1, regionType, null, shortcut.name(),
          regionName, new int[] {locatorPort});

      invokeRunnableInVMs(invokeCreateRegion(regionName, shortcut.name()), server2);
      try {
        server1.invoke(() -> createLuceneIndexOnExistingRegion(cache, regionName, INDEX_NAME));
        fail();
      } catch (Exception exception) {
        if (!exception.getCause().getCause().getMessage()
            .contains("are not the same Apache Geode version")) {
          exception.printStackTrace();
          fail();
        }
      }

      int expectedRegionSize = 10;
      putSerializableObject(server1, regionName, 0, expectedRegionSize);

      server2 = rollServerToCurrentAndCreateRegionOnly(server2, regionType, null, shortcut.name(),
          regionName, new int[] {locatorPort});


      AsyncInvocation ai1 = server1
          .invokeAsync(() -> createLuceneIndexOnExistingRegion(cache, regionName, INDEX_NAME));

      AsyncInvocation ai2 = server2
          .invokeAsync(() -> createLuceneIndexOnExistingRegion(cache, regionName, INDEX_NAME));

      ai1.join();
      ai2.join();

      ai1.checkException();
      ai2.checkException();

      expectedRegionSize += 10;
      putSerializableObjectAndVerifyLuceneQueryResult(server2, regionName, expectedRegionSize, 15,
          25, server1, server2);

    } finally {
      invokeRunnableInVMs(true, invokeStopLocator(), locator1);
      invokeRunnableInVMs(true, invokeCloseCache(), server1, server2);
    }
  }


}

@@ -974,16 +974,81 @@
 .fail;%0A%0A
+import org.assertj.core.api.Assertions;%0Aimport org.junit.Assume;%0A
 import o
@@ -1225,16 +1225,72 @@
 Helper;%0A
+import org.apache.geode.internal.serialization.Version;%0A
 import o
@@ -1767,16 +1767,157 @@
 ption %7B%0A
+    Assume.assumeFalse(%22minor versions should be different%22,%0A        majorMinor(oldVersion).equals(majorMinor(Version.CURRENT.getName())));%0A%0A
     fina
@@ -4863,11 +4863,276 @@
  %7D%0A  %7D%0A%0A
+  /**%0A   * returns the major.minor prefix of a semver%0A   */%0A  private static String majorMinor(String version) %7B%0A    String%5B%5D parts = version.split(%22%5C%5C.%22);%0A    Assertions.assertThat(parts.length).isGreaterThanOrEqualTo(2);%0A    return parts%5B0%5D + %22.%22 + parts%5B1%5D;%0A  %7D%0A
 %0A%7D%0A

fix lucene test to not hang on support branches (#4999)