#!/bin/sh
# Determine the translation options and translate

set -e -u

usage() {
	name=$(basename $0)
	echo <<EOF
Usage: $name [options...]"
Options:
  --python=PYTHON Use PYTHON to tranlate PyPy

EOF
}

PYTHON=python

while [ $# -ge 1 ]; do
	case "$1" in
	--python)
		PYTHON="$2"
		shift
		;;
	--help|-h)
		usage
		exit 0
		;;
	*)
		echo "Unkown option: $1" >&2
		usage
		exit 1
		;;
	esac
	shift
done

RPYOPTS="--batch --source"
TARGETOPTS=""

OPT=3
ROOTFINDER=shadowstack
if echo "$DEB_BUILD_OPTIONS" | egrep -q '\bnoopt\b'; then
	OPT=0
elif dpkg-architecture -iany-i386; then
	OPT=jit
	ROOTFINDER=asmgcc
	#RPYOPTS="$RPYOPTS --jit-backend=x86-without-sse2"
elif dpkg-architecture -iany-amd64; then
	# No JIT on x32
	if ! dpkg-architecture -elinux-x32; then
		OPT=jit
	fi
	ROOTFINDER=asmgcc
elif dpkg-architecture -iany-arm; then
	# No JIT support for ARMv5
	if ! dpkg-architecture -elinux-armel; then
		OPT=jit
	fi
elif dpkg-architecture -iany-ppc64el || dpkg-architecture -iany-ppc64; then
	OPT=jit
elif dpkg-architecture -iany-s390x; then
	OPT=jit
fi
RPYOPTS="$RPYOPTS --opt=$OPT --shared"

if [ $OPT = 3 ]; then
	RPYOPTS="$RPYOPTS --no-profopt"
fi

if [ $OPT = "mem" -o $OPT = "jit" -o $OPT = 2 -o $OPT = 3 ]; then
	RPYOPTS="$RPYOPTS --gcrootfinder=$ROOTFINDER"
fi

CONTINUATION=0
if dpkg-architecture -iany-i386 \
   || dpkg-architecture -iany-amd64 \
   || dpkg-architecture -iany-arm \
   || dpkg-architecture -iany-mips64el \
   || dpkg-architecture -iany-ppc64 \
   || dpkg-architecture -iany-ppc64el \
   || dpkg-architecture -iany-s390x; then
	CONTINUATION=1
fi
if [ $CONTINUATION -eq 0 ]; then
	TARGETOPTS="$TARGETOPTS --withoutmod-_continuation"
fi

if dpkg-architecture -iany-s390x; then
	# Target the oldest s390x supported by upstream
	export CFLAGS="$CFLAGS -march=z10"
fi

if echo "$PYTHON" | grep -Fq pypy; then
	if [ $(dpkg-architecture -q DEB_HOST_ARCH_BITS) -eq 32 ]; then
		export PYPY_GC_MAX_DELTA=200MB
		PYTHON="$PYTHON --jit loop_longevity=300"
	fi
fi

RPYTHON="$(pwd)/rpython/bin/rpython"

set -x
cd pypy/goal
exec $PYTHON -u $RPYTHON $RPYOPTS targetpypystandalone $TARGETOPTS 2>&1
