#!/bin/bash
# Copyright (C) 2024 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.

# Script to help parse java command line options.
#
# Useful to use it in a "soong-rerun" script generated by
# extract-last-soong-commands.py.
#
# Usage:
#
#   A javac invocation in a  soong-rerun script contains looks like this:
#
#   -----------------------------
#   out/host/linux-x86/bin/soong_javac_wrapper prebuilts/jdk/jdk21/linux-x86/bin/javac [JAVAC OPTIONS...]
#   -----------------------------
#
#   Just inject this script like so, between "soong_javac_wrapper" and the actual javac command:
#   -----------------------------
#   out/host/linux-x86/bin/soong_javac_wrapper $ANDROID_BUILD_TOP/frameworks/base/ravenwood/scripts/javac-arg-dumper.sh prebuilts/jdk/jdk21/linux-x86/bin/javac ...
#   -----------------------------
#
# Then run the rerun script.

javac="$1"
shift

options=("$@")

echo "JAVAC: $javac"

dump_array() {
    local prefix="$1"   # Prefix for the output.
    local toplevel="$2" # 1 for a "toplevel" dump. 0 for nested dump.
    shift 2

    local arg
    for arg in "$@"; do
        # Print each argument with shell-escaping.
        echo "${prefix}${arg%Q}"

        # If the argument is a jar file and it exists, print its content.
        # (if it contains multiple jar files joined with ':'s, then it'll
        # fail the -f test. In that case, we'll dump each jar in a nested dump.)
        if [[ "$arg" =~ \.jar$ ]] && [[ -f "$arg" ]] ; then
            echo "      jar tf $arg"
            jar tf "$arg" | sed -e 's/^/        /'
        fi

        # If we're at the toplevel, we want to do extra dump.
        if ! (( $toplevel )) ; then
            continue
        fi

        # If it's a a *.rsp file, print its content.
        if [[ "$arg" =~ ^@ ]] ; then
            local rsp_file=${arg:1}
            sed -e 's/^/    RSP: /' "$rsp_file"
            continue
        fi

        # If the argument contains ':', then split it and do a nested dump.
        if [[ "$arg" =~ : ]] ; then
            dump_array "    SPLIT: " 0 $(tr -s ':' ' ' <<<"$arg")
            continue
        fi

    done
}

# Dump the arguments.
dump_array "ARG: " 1 "${options[@]}"

# Use `export JAVA_ARG_DUMPER_DRY=1` if you don't want to run javac.
if (( $JAVA_ARG_DUMPER_DRY )) ; then
    echo
    echo "Dry-run, not running javac." 1>&2
    exit 13
fi

echo-and-exec() {
    echo "$@"
    exec "$@"
}

echo-and-exec "$javac" "${options[@]}"
