#!/bin/bash
# Copyright 2023 gRPC authors.
#
# 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.

set -ex

cd "$(dirname $0)"

PLATFORM="$1"
if [[ "$PLATFORM" == "" ]]; then
  echo "first argument must be a ruby gem platform"
  exit 1
fi

if ! test -d symbols; then
  echo "directory $(pwd)/symbols should exist and be populated with .dbg symbolf files before running this script"
  exit 1
fi
for f in "$(ls symbols)"; do
  echo "checking symbol file: $f"
  if [[ "$f" != *.dbg ]]; then
    echo "symbol file names should end in .dbg"
    exit 1
  fi
done

rm -r tmp || true
rm -r pkg || true
mkdir -p tmp
mkdir -p pkg

# we need to generate some package contents dynamically
cp -p grpc-native-debug.gemspec tmp
cp -p README.md tmp
cp -p version.rb tmp
cp -p platform.rb tmp
sed -i "s/# GENERATED BY BUILD_PACKAGES SCRIPT/'${PLATFORM}'/" tmp/platform.rb
mkdir -p tmp/symbols
cp -p symbols/*"$PLATFORM"*.dbg tmp/symbols

# build
cd tmp
gem build grpc-native-debug.gemspec
cp grpc-native-debug*.gem ../pkg
