#!/bin/bash
#
# Copyright 2025 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.
#
# Generates jvm_module_options.h from a deploy jar's manifest.

set -euo pipefail

if [[ $# -ne 2 ]]; then
  echo "Usage: $0 <jar_file> <output_file>" >&2
  exit 1
fi

JAR_FILE=$1
OUTPUT_FILE=$2

cat > "${OUTPUT_FILE}" <<'EOF'
// Automatically generated by //third_party/bazel/src/main/cpp:BUILD.

#ifndef THIRD_PARTY_BAZEL_SRC_MAIN_CPP_JVM_MODULE_OPTIONS_H_
#define THIRD_PARTY_BAZEL_SRC_MAIN_CPP_JVM_MODULE_OPTIONS_H_

#include <string>
#include <vector>

namespace blaze {

inline std::vector<std::string> getJvmModuleOptions() {
  return {
EOF

if [[ -f "${JAR_FILE}" ]]; then
  # Extract options from manifest:
  # We first join continuation lines in the manifest, then grep for the headers we
  # care about, and then process them.
  unzip -p "${JAR_FILE}" META-INF/MANIFEST.MF 2>/dev/null | \
      sed -e 's/\r$//' | sed -e ':a' -e 'N' -e '$!ba' -e 's/\n / /g' | \
      grep -E '^(Add-Exports|Add-Opens):' | \
      while read -r line; do
          if [[ "$line" =~ ^Add-Exports: ]]; then
              key="--add-exports"
              values="${line#Add-Exports: }"
          elif [[ "$line" =~ ^Add-Opens: ]]; then
              key="--add-opens"
              values="${line#Add-Opens: }"
          else
              continue
          fi
          for val in $values; do
              echo "    \"$key\", \"$val=ALL-UNNAMED\"," >> "${OUTPUT_FILE}"
          done
      done || true
  # The '|| true' is to prevent build failures if grep finds nothing, which would cause
  # the read to fail and the pipe to exit with a non-zero status.
fi

cat >> "${OUTPUT_FILE}" <<'EOF'
  };
}

}  // namespace blaze
#endif  // THIRD_PARTY_BAZEL_SRC_MAIN_CPP_JVM_MODULE_OPTIONS_H_
EOF
