#!/usr/bin/env bash
set -e

src_dir="${0%/*}"

if [ -z "$CC" ]; then
  if type -p gcc >/dev/null; then
    CC=gcc
  else
    echo "warning: gcc not found; using CC=cc" >&2
    CC=cc
  fi
fi

if ! type -p "$CC" >/dev/null; then
  echo "aborted: compiler not found: $CC" >&2
  exit 1
fi

case "$(uname -s)" in
Darwin* )
  host_os="darwin$(uname -r)"
  ;;
FreeBSD* )
  host_os="freebsd$(uname -r)"
  ;;
OpenBSD* )
  host_os="openbsd$(uname -r)"
  ;;
* )
  host_os="linux-gnu"
esac

eval "$("$src_dir"/shobj-conf -C "$CC" -o "$host_os")"

sed "
  s#@CC@#${CC}#
  s#@CFLAGS@#${CFLAGS}#
  s#@LOCAL_CFLAGS@#${LOCAL_CFLAGS}#
  s#@DEFS@#${DEFS}#
  s#@LOCAL_DEFS@#${LOCAL_DEFS}#
  s#@SHOBJ_CC@#${SHOBJ_CC}#
  s#@SHOBJ_CFLAGS@#${SHOBJ_CFLAGS}#
  s#@SHOBJ_LD@#${SHOBJ_LD}#
  s#@SHOBJ_LDFLAGS@#${SHOBJ_LDFLAGS}#
  s#@SHOBJ_XLDFLAGS@#${SHOBJ_XLDFLAGS}#
  s#@SHOBJ_LIBS@#${SHOBJ_LIBS}#
  s#@SHOBJ_STATUS@#${SHOBJ_STATUS}#
" "$src_dir"/Makefile.in > "$src_dir"/Makefile
