#!/usr/bin/env bash

#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you 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.
#

MKTEMP="mktemp /tmp/tmp.XXXXXXXXXX"

rc=0
syms_desired=$($MKTEMP)
syms_library=$($MKTEMP)
syms_missing=$($MKTEMP)
syms_extra=$($MKTEMP)

trap 'rm $syms_desired $syms_library $syms_missing $syms_extra' EXIT

if [[ $# -lt 2 ]] ; then
  echo "Usage:"
  echo "check_abi object_file expected_symbols_file"
  exit 1;
fi

LC_ALL=C
export LC_ALL

# Extract exported symbols from library
nm -DC --defined-only -f s $1 | cut -f1 -d'|' -s | sed -e "$(./cppabi)" -e "s/ *$//" | sort -u > $syms_library

# Process API syms (substitute in some typedefs etc.)
sed -e "
    $(./expand_types)
    /^\$/d
    /^#.*\$/d
" $2 | sort -u > $syms_desired

comm -23 $syms_desired $syms_library > $syms_missing
comm -13 $syms_desired $syms_library > $syms_extra

if [[ -n "$(cat $syms_missing)" ]] ; then
  (echo "Not exported from library (should be)"
   echo "====================================="
   cat $syms_missing ) 1>&2
   rc=1
fi


if [[ -n "$(cat $syms_extra)" ]]; then
  (echo "Exported by library but not in spec"
   echo "==================================="
   cat $syms_extra ) 1>&2
fi

exit $rc
