// Copyright (C) 2018 The Android Open Source Project
//
// 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 com.google.gerrit.server.config;

import com.google.gerrit.common.Nullable;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import org.eclipse.jgit.lib.Config;

/** Provides {@link GerritInstanceName} from {@code gerrit.name}. */
@Singleton
public class GerritInstanceNameProvider implements Provider<String> {
  private final String instanceName;

  @Inject
  public GerritInstanceNameProvider(
      @GerritServerConfig Config config,
      @CanonicalWebUrl @Nullable Provider<String> canonicalUrlProvider) {
    this.instanceName = getInstanceName(config, canonicalUrlProvider);
  }

  private String getInstanceName(Config config, @Nullable Provider<String> canonicalUrlProvider) {
    String instanceName = config.getString("gerrit", null, "instanceName");
    if (instanceName != null || canonicalUrlProvider == null) {
      return instanceName;
    }

    return canonicalUrlProvider.get();
  }

  @Override
  public String get() {
    return instanceName;
  }
}

@@ -801,35 +801,138 @@
 ort 
-org.eclipse.jgit.lib.Config
+java.net.MalformedURLException;%0Aimport java.net.URL;%0Aimport org.eclipse.jgit.lib.Config;%0Aimport org.eclipse.jgit.util.SystemReader
 ;%0A%0A/
@@ -1358,23 +1358,96 @@
 %0A  %7D%0A%0A  
-private
+@Override%0A  public String get() %7B%0A    return instanceName;%0A  %7D%0A%0A  private static
  String 
@@ -1462,16 +1462,23 @@
 nceName(
+%0A      
 Config c
@@ -1720,16 +1720,36 @@
  return 
+extractInstanceName(
 canonica
@@ -1766,16 +1766,17 @@
 er.get()
+)
 ;%0A  %7D%0A%0A 
@@ -1780,65 +1780,499 @@
 %0A%0A  
-@Override%0A  public String get() %7B%0A    return instanceN
+private static String extractInstanceName(String canonicalUrl) %7B%0A    if (canonicalUrl != null) %7B%0A      try %7B%0A        return new URL(canonicalUrl).getHost();%0A      %7D catch (MalformedURLException e) %7B%0A        // Try something else.%0A      %7D%0A    %7D%0A%0A    // Fall back onto whatever the local operating system thinks%0A    // this server is called. We hopefully didn't get here as a%0A    // good admin would have configured the canonical url.%0A    //%0A    return SystemReader.getInstance().getHostn
 ame
+()
 ;%0A  

Parse the canonical URL for the instance name