/*
 * Copyright 2017 Google, Inc.
 *
 * 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.netflix.spinnaker.halyard.core.registry.v1;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.storage.Storage;
import com.google.api.services.storage.StorageScopes;
import com.netflix.spinnaker.halyard.core.provider.v1.google.GoogleCredentials;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.Yaml;

@Component
@Slf4j
@ConditionalOnProperty("spinnaker.config.input.gcs.enabled")
public class GoogleProfileReader implements ProfileReader {
  @Autowired String spinconfigBucket;

  @Autowired Storage applicationDefaultGoogleStorage;

  @Autowired Storage unauthenticatedGoogleStorage;

  @Autowired ObjectMapper relaxedObjectMapper;

  @Autowired Yaml yamlParser;

  @Bean
  public Storage applicationDefaultGoogleStorage() {
    return createGoogleStorage(true);
  }

  @Bean
  public Storage unauthenticatedGoogleStorage() {
    return createGoogleStorage(false);
  }

  public InputStream readProfile(String artifactName, String version, String profileName)
      throws IOException {
    String path = profilePath(artifactName, version, profileName);
    return getContents(path);
  }

  public BillOfMaterials readBom(String version) throws IOException {
    String bomName = bomPath(version);

    return relaxedObjectMapper.convertValue(
        yamlParser.load(getContents(bomName)), BillOfMaterials.class);
  }

  public Versions readVersions() throws IOException {
    return relaxedObjectMapper.convertValue(
        yamlParser.load(getContents("versions.yml")), Versions.class);
  }

  public InputStream readArchiveProfile(String artifactName, String version, String profileName)
      throws IOException {
    return readProfile(artifactName, version, profileName + ".tar.gz");
  }

  String profilePath(String artifactName, String version, String profileFileName) {
    return String.join("/", artifactName, version, profileFileName);
  }

  String bomPath(String version) {
    return String.join("/", "bom", version + ".yml");
  }

  private InputStream getContents(String objectName) throws IOException {
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    log.info("Getting object contents of " + objectName);

    try {
      applicationDefaultGoogleStorage
          .objects()
          .get(spinconfigBucket, objectName)
          .executeMediaAndDownloadTo(output);
    } catch (IOException e) {
      log.debug(
          "Getting object contents of {} failed. Retrying with no authentication.", objectName, e);
      output = new ByteArrayOutputStream();
      unauthenticatedGoogleStorage
          .objects()
          .get(spinconfigBucket, objectName)
          .executeMediaAndDownloadTo(output);
    }

    return new ByteArrayInputStream(output.toByteArray());
  }

  private Storage createGoogleStorage(boolean useApplicationDefaultCreds) {
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    String applicationName = "Spinnaker/Halyard";
    HttpRequestInitializer requestInitializer;

    try {
      com.google.auth.oauth2.GoogleCredentials credentials =
          useApplicationDefaultCreds
              ? com.google.auth.oauth2.GoogleCredentials.getApplicationDefault()
              : com.google.auth.oauth2.GoogleCredentials.newBuilder().build();
      if (credentials.createScopedRequired()) {
        credentials =
            credentials.createScoped(Collections.singleton(StorageScopes.DEVSTORAGE_FULL_CONTROL));
      }
      requestInitializer = GoogleCredentials.setHttpTimeout(credentials);

      log.info("Loaded application default credential for reading BOMs & profiles.");
    } catch (Exception e) {
      requestInitializer = GoogleCredentials.retryRequestInitializer();
      log.debug(
          "No application default credential could be loaded for reading BOMs & profiles. Continuing unauthenticated: {}",
          e.getMessage());
    }

    return new Storage.Builder(
            GoogleCredentials.buildHttpTransport(), jsonFactory, requestInitializer)
        .setApplicationName(applicationName)
        .build();
  }
}

@@ -4175,92 +4175,26 @@
 izer
-;%0A%0A    try %7B%0A      com.google.auth.oauth2.GoogleCredentials credentials =%0A          
+ = null;%0A%0A    if (
 useA
@@ -4219,24 +4219,31 @@
 reds
+) %7B
 %0A      
+try %7B%0A
        
- ?
  com
@@ -4283,32 +4283,22 @@
 ials
-.getApplicationDefault()
+ credentials =
 %0A   
@@ -4309,12 +4309,8 @@
     
-   :
  com
@@ -4351,30 +4351,35 @@
 als.
-newBuilder().build
+getApplicationDefault
 ();%0A
+  
     
@@ -4422,32 +4422,34 @@
 ed()) %7B%0A        
+  
 credentials =%0A  
@@ -4438,32 +4438,34 @@
   credentials =%0A
+  
             cred
@@ -4485,16 +4485,35 @@
 eScoped(
+%0A                  
 Collecti
@@ -4563,24 +4563,26 @@
 _CONTROL));%0A
+  
       %7D%0A    
@@ -4579,24 +4579,26 @@
     %7D%0A      
+  
 requestIniti
@@ -4653,17 +4653,18 @@
 tials);%0A
-%0A
+  
       lo
@@ -4741,24 +4741,26 @@
 les.%22);%0A    
+  
 %7D catch (Exc
@@ -4777,78 +4777,8 @@
 %7B%0A  
-    requestInitializer = GoogleCredentials.retryRequestInitializer();%0A
     
@@ -4782,32 +4782,34 @@
      log.debug(%0A
+  
           %22No ap
@@ -4925,16 +4925,18 @@
         
+  
 e.getMes
@@ -4940,24 +4940,148 @@
 Message());%0A
+      %7D%0A    %7D%0A    if (requestInitializer == null) %7B%0A      requestInitializer = GoogleCredentials.retryRequestInitializer();%0A
     %7D%0A%0A    r

fix anonymous Google storage credentials (#1462)