#!/bin/sh

set -e

LJARCH=
LUAJIT_BUILDMODE=
LUAJIT_BUILDVM_X=
LUAJIT_DASM_ARCHS=
LUAJIT_PREFIX=
for OPTION; do
    case "${OPTION}" in
	--prefix=*)
		LUAJIT_PREFIX="${OPTION#--prefix=}"
		;;
	BUILDMODE=*)
		LUAJIT_BUILDMODE="${OPTION#BUILDMODE=}"
		;;
	BUILDVM_X=*)
		LUAJIT_BUILDVM_X="${OPTION#BUILDVM_X=}"
		;;
	DASM_ARCHS=*)
		LUAJIT_DASM_ARCHS="${OPTION#DASM_ARCHS=}"
		;;
	LJARCH=*)
		LJARCH="${OPTION#LJARCH=}"
		;;
	esac
done

cat > Makefile.vcpkg <<END_MAKEFILE ;

COMMON_OPTIONS += 'E=@:' 'Q='
COMMON_OPTIONS += 'BUILDMODE=${LUAJIT_BUILDMODE}'
COMMON_OPTIONS += 'PREFIX=${LUAJIT_PREFIX}'
COMMON_OPTIONS += 'INSTALL_TNAME=luajit'

BUILD_OPTIONS += 'CC=${CC}'
BUILD_OPTIONS += 'CCDEBUG='
BUILD_OPTIONS += 'CFLAGS=${CPPFLAGS} ${CFLAGS}'
BUILD_OPTIONS += 'LDFLAGS=${LDFLAGS}'
BUILD_OPTIONS += 'LIBS=${LIBS}'

ifeq (${LJARCH},)
# native
BUILDVM_PREFIX = ${LUAJIT_PREFIX}/manual-tools/luajit
DASM_ARCHS = ${LUAJIT_DASM_ARCHS}
else
# cross
BUILD_OPTIONS += 'HOST_CC=:'
BUILD_OPTIONS += 'BUILDVM_T='
BUILD_OPTIONS += 'BUILDVM_X=${LUAJIT_BUILDVM_X}'
endif

# used by src/Makefile, best effort from manual '<CC> [-m32] -E src/lj_arch.h -dM'
TARGET_TESTARCH_COMMON += 'LJ_LE 1' 'LJ_HASJIT 1' 'LJ_HASFFI 1' 'LJ_ARCH_HASFPU 1' 'LJ_ABI_SOFTFP 0'
TARGET_TESTARCH_COMMON_32 += \$(TARGET_TESTARCH_COMMON) 'LJ_ARCH_BITS 32'
TARGET_TESTARCH_COMMON_64 += \$(TARGET_TESTARCH_COMMON) 'LJ_ARCH_BITS 64' 'LJ_TARGET_GC64 1'
TARGET_TESTARCH_arm =   \$(TARGET_TESTARCH_COMMON_32) LJ_TARGET_ARM
TARGET_TESTARCH_arm64 = \$(TARGET_TESTARCH_COMMON_64) LJ_TARGET_ARM64 'LJ_ARCH_VERSION 80'
TARGET_TESTARCH_x86 =   \$(TARGET_TESTARCH_COMMON_32) LJ_TARGET_X86
TARGET_TESTARCH_x64 =   \$(TARGET_TESTARCH_COMMON_64) LJ_TARGET_X64 'LJ_FR2 1'

all:
	\$(MAKE) clean \$(COMMON_OPTIONS) \$(BUILD_OPTIONS)
	\$(MAKE) all \$(COMMON_OPTIONS) \$(BUILD_OPTIONS)
	for DA in \$(DASM_ARCHS); do \\
	    rm -f src/host/buildvm_arch.h src/host/*.o; \\
	    case "\$\$DA" in \\
	      arm)   TARGET_TESTARCH="\$(TARGET_TESTARCH_arm)" ;; \\
	      arm64) TARGET_TESTARCH="\$(TARGET_TESTARCH_arm64)" ;; \\
	      x86)   TARGET_TESTARCH="\$(TARGET_TESTARCH_x86)" ;; \\
	      x64)   TARGET_TESTARCH="\$(TARGET_TESTARCH_x64)" ;; \\
	    esac ; \\
	    \$(MAKE) -C src host/buildvm-\$\$DA\$(EXECUTABLE_SUFFIX) \$(COMMON_OPTIONS) \$(BUILD_OPTIONS) \\
	      BUILDVM_T=host/buildvm-\$\$DA\$(EXECUTABLE_SUFFIX) "TARGET_TESTARCH=\$\${TARGET_TESTARCH}" \\
	    || exit 1; \\
	done

install:
	\$(MAKE) install \$(COMMON_OPTIONS)
	for DA in \$(DASM_ARCHS); do \\
		mkdir -p "\$\${DESTDIR}\$(BUILDVM_PREFIX)"; \\
		install -m 0755 "src/host/buildvm-\$\$DA\$(EXECUTABLE_SUFFIX)" "\$\${DESTDIR}\$(BUILDVM_PREFIX)/buildvm-\$\$DA\$(EXECUTABLE_SUFFIX)" || exit 1 ; \\
	done

END_MAKEFILE
