// Copyright 2019 The Bazel Authors. All rights reserved.
//
// 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.devtools.build.android;

import static com.google.common.collect.ImmutableList.toImmutableList;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.devtools.build.android.aapt2.Aapt2ConfigOptions;
import com.google.devtools.common.options.OptionsParser;
import com.google.devtools.common.options.ShellQuotedParamsFilePreProcessor;
import java.nio.file.FileSystems;
import java.util.List;
import java.util.logging.Logger;

/**
 * A {@link ResourceProcessorBusyBox} action which executes {@code aapt2 optimize}, passing through
 * raw arguments.
 */
class Aapt2OptimizeAction {
  private static final Logger logger = Logger.getLogger(Aapt2OptimizeAction.class.getName());

  public static void main(String... args) throws Exception {
    logger.fine(CommandHelper.execute("Optimizing resources", buildCommand(args)));
  }

  @VisibleForTesting
  static List<String> buildCommand(String... args) {
    OptionsParser optionsParser =
        OptionsParser.builder()
            .optionsClasses(Aapt2ConfigOptions.class)
            .argsPreProcessor(new ShellQuotedParamsFilePreProcessor(FileSystems.getDefault()))
            .allowResidue(true)
            .build();
    optionsParser.parseAndExitUponError(args);

    ImmutableList<String> rawOptimizeArgs =
        optionsParser.getResidue().stream()
            .map(
                arg -> {
                  // Translate new (i.e. soon to be renamed) flag into current flag, pending an
                  // upcoming aapt2 update.
                  // TODO(bcsf): Prior to the aapt2 drop which introduces the renamed flag, add a
                  //   check to determine whether this mapping needs to be performed.
                  switch (arg) {
                    case "--enable-resource-name-obfuscation":
                      return "--enable-resource-obfuscation";
                    case "--resource-name-obfuscation-exemption-list":
                      return "--whitelist-path";
                    default:
                      return arg;
                  }
                })
            .collect(toImmutableList());
    return ImmutableList.<String>builder()
        .add(optionsParser.getOptions(Aapt2ConfigOptions.class).aapt2.toString())
        .add("optimize")
        .addAll(rawOptimizeArgs)
        .build();
  }

  private Aapt2OptimizeAction() {}
}

@@ -2014,179 +2014,279 @@
     
-.map(%0A                arg -%3E %7B%0A                  // Translate new (i.e. soon to be renamed) flag into current flag, pending an%0A                  // upcoming aapt2 update.%0A
+// TODO(b/141204955): Remove these mapping hacks once some dust has settled.%0A            .map(%0A                arg -%3E %7B%0A                  switch (arg) %7B%0A                    case %22--shorten-resource-paths%22:%0A                    case %22--enable-resource-path-shortening%22:%0A   
     
@@ -2295,26 +2295,27 @@
             
-//
+ /*
  TODO(bcsf):
@@ -2319,254 +2319,496 @@
 f): 
-Prior to the aapt2 drop which introduces the renamed flag, add a%0A                  //   check to determine whether this mapping needs to be performed.%0A                  switch (arg) %7B%0A                    case %22--enable-resource-name-obfuscation%22:
+Start using this at the time we drop AAPT2 5880457.%0A                      return %22--shorten-resource-paths%22;%0A                      */%0A                      return %22--enable-resource-path-shortening%22;%0A                    case %22--collapse-resource-names%22:%0A                    case %22--enable-resource-name-obfuscation%22:%0A                      /* TODO(bcsf): Start using this at the time we drop AAPT2 5880457.%0A                      return %22--collapse-resource-names%22;%0A                      */
 %0A   
@@ -2937,16 +2937,79 @@
 -list%22:%0A
+                      // TODO(bcsf): This case goes away soon.%0A
         

Improve preparation for flag changes which will come out with an upcoming AAPT2 version.