#!/usr/bin/make -f
export DH_VERBOSE = 1
export deb_build_dir = /tmp/deb_build
export name = occlum-toolchains-gcc
export buildroot := $(deb_build_dir)/$(name)/debian/$(name)

export tmp_build_dir = $(deb_build_dir)/$(name)/tmp_build
export install_dir = $(buildroot)/opt/occlum/toolchains/gcc

SHELL = /bin/bash

# Needed by musl-cross-make config
TARGET = x86_64-linux-musl
MUSL_REPO = https://github.com/occlum/musl
MUSL_VER = 1.1.24
GCC_VER = 8.3.0

# Users can pass "-j$(nproc)" by specifying this env.
# This is not enabled by default because under certain scenarios,
# make will use too many jobs and gcc will be killed because out
# of memory.
BUILD_OPTIONS +=

.ONESHELL: prepare_musl override_dh_install

%:
	dh $@

# All rules executed in one shell
prepare_musl:
	rm -rf $(tmp_build_dir)
	rm -rf $(install_dir)
	mkdir -p $(tmp_build_dir)
	cd $(tmp_build_dir)
	git clone https://github.com/occlum/musl-cross-make
	cd musl-cross-make
	git checkout 0.9.9.hotfix
	cp $(deb_build_dir)/$(name)/debian/0014-libgomp-*.diff patches/gcc-$(GCC_VER)
	cat > config.mak <<EOF
		TARGET = $(TARGET)
		OUTPUT = $(install_dir)
		COMMON_CONFIG += CFLAGS="-fPIC" CXXFLAGS="-fPIC" LDFLAGS="-pie"
		GCC_VER = $(GCC_VER)
		MUSL_VER = git-$(MUSL_VER)
		MUSL_REPO = $(MUSL_REPO)
	EOF

override_dh_auto_build: prepare_musl
	cd $(tmp_build_dir)/musl-cross-make; \
		make $(BUILD_OPTIONS)

# We create symlinks in /usr/local
override_dh_usrlocal:
	echo "Skip ..."

override_dh_fixperms:
	dh_fixperms
	# Occlum need this to be executable
	chmod 755 $(install_dir)/$(TARGET)/lib/libc.so

override_dh_install:
	cd $(tmp_build_dir)/musl-cross-make
	make install
	cat > $(install_dir)/bin/occlum-gcc <<EOF
		#!/bin/bash
		/opt/occlum/toolchains/gcc/bin/$(TARGET)-gcc -fPIC -pie -Wl,-rpath,/opt/occlum/toolchains/gcc/$(TARGET)/lib "\$$@"
	EOF

	cat > $(install_dir)/bin/occlum-g++ <<EOF
		#!/bin/bash
		/opt/occlum/toolchains/gcc/bin/$(TARGET)-g++ -fPIC -pie -Wl,-rpath,/opt/occlum/toolchains/gcc/$(TARGET)/lib "\$$@"
	EOF

	cat > $(install_dir)/bin/occlum-ld <<EOF
		#!/bin/bash
		/opt/occlum/toolchains/gcc/bin/$(TARGET)-ld -pie -rpath /opt/occlum/toolchains/gcc/$(TARGET)/lib "\$$@"
	EOF

	chmod +x $(install_dir)/bin/occlum-gcc
	chmod +x $(install_dir)/bin/occlum-g++
	chmod +x $(install_dir)/bin/occlum-ld

	mkdir -p $(buildroot)/lib
	pushd $(buildroot)/lib
	ln -sf /opt/occlum/toolchains/gcc/$(TARGET)/lib/libc.so ld-musl-x86_64.so.1
	popd
	mkdir -p $(buildroot)/usr/local
	pushd $(buildroot)/usr/local
	ln -sf /opt/occlum/toolchains/gcc occlum
	popd
	pushd $(install_dir)/bin
	ln -sf /opt/occlum/toolchains/gcc/bin/x86_64-linux-musl-gcc-ar occlum-ar
	ln -sf /opt/occlum/toolchains/gcc/bin/x86_64-linux-musl-strip occlum-strip
	popd

	mkdir -p $(buildroot)/etc/profile.d
	cp $(deb_build_dir)/$(name)/debian/occlum-gcc.sh $(buildroot)/etc/profile.d
	chmod 644 $(buildroot)/etc/profile.d/occlum-gcc.sh

clean:
	dh_clean
	rm -f $(buildroot)

override_dh_shlibdeps:
	echo "skip ..."
