#! /bin/bash
# script to compile C programs that are linked 
# against Fortran libraries
# last modified 12 Oct 21 th

exec 3>&2
exec 2> /tmp/fcc.log.$$
set -x

args=
compileonly=
objs=
ldflags=
fldflags="-Wl,-z,relro -L/usr/libexec/gcc/x86_64-linux-gnu/15/liblto_plugin.so -L/usr/lib/gcc/x86_64-linux-gnu/15 -L/usr/lib/gcc/x86_64-linux-gnu/15/../../../x86_64-linux-gnu -L/usr/lib/gcc/x86_64-linux-gnu/15/../../../../lib -L/lib/x86_64-linux-gnu -L/lib/../lib -L/usr/lib/x86_64-linux-gnu -L/usr/lib/../lib -L/usr/lib/gcc/x86_64-linux-gnu/15/../../.. -L/lib -L/usr/lib -lgfortran -lm -lgcc_s -lgcc -lquadmath -lm -lgcc_s -lgcc -lpthread -lrt"
cdefs="-DQUAD=0 -DQUADSIZE=16 -DNOUNDERSCORE=0 -DBIGENDIAN=0"

cc="${REALCC:-gcc -g -O2 -Werror=implicit-function-declaration -ffile-prefix-map=/build/reproducible-path/looptools-2.16=. -fstack-protector-strong -fstack-clash-protection -Wformat -Werror=format-security -fcf-protection -m64}"
cc+=" $cdefs"
cxx="${REALCXX:-g++ -g -O2 -ffile-prefix-map=/build/reproducible-path/looptools-2.16=. -fstack-protector-strong -fstack-clash-protection -Wformat -Werror=format-security -fcf-protection -m64 -stdlib=libstdc++}"
cxx+=" $cdefs"
[[ "${0%.in}" =~ f++$ ]] && cc="$cxx"

while test $# -gt 0; do
  printf -v arg "%q" "$1"
  case "$1" in
  -st | -b32 | -b64)
	;; # ignore mcc-specific flags
  -arch)
	shift
	;;
  -lstdc++)
	cc="$cxx"
	;; # or else -static-libstdc++ has no effect
  -Wno-long-double)
	;; # mcc adds this on Macs & gcc 4 doesn't like it
  -L*CompilerAdditions*)
	ldflags+=" $arg"
	mldir="${1#-L}"
	mldir="${mldir%%CompilerAdditions*}"
	mldir="${mldir/Links\/MathLink\/DeveloperKit/Libraries}"
	[[ "$cc" == *-m32* ]] && mldir="${mldir//-x86-64}"
	test -f "$mldir/libuuid.a" && ldflags+=" -L'$mldir'" fldflags+=" -luuid"
	;;
  -[Ll]* | -Wl*)
	ldflags+=" $arg"
	;;
  *.tm.o)
	objs="$arg $objs"
	;;
  *.a | *.o | *.so)
	objs+=" $arg"
	;;
  *.cc)
	args+=" $arg"
	cc="$cxx"
	;;
  -c)
	compileonly="-c"
	;;
  -o)
	args+=" -o '$2'"
	shift
	;;
  *.tm.c)
	args+=" $arg"
	tmc+=" $arg"
	;;
  *)
	args+=" $arg"
	tmargs+=" $arg"
	;;
  esac
  shift
done

test -n "$DEBUG" && for tm in $tmc; do
  eval "$cc $tmargs -E -P -o ${tm//.c}.i $tm 2>&3"
done

eval "set -x; exec $cc $args ${compileonly:-$objs $ldflags $fldflags} 2>&3"

