#!/bin/sh
#
# Copyright (c) 2019 David Demelier <markand@malikania.fr>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

PKGNAME=clang
PKGVERSION=8.0.1
PKGREVISION=1
PKGLICENSE="MIT CUSTOM"
PKGSUMMARY="C language family frontend for LLVM"
PKGDOWNLOAD="https://github.com/llvm/llvm-project/releases/download/llvmorg-$PKGVERSION/cfe-$PKGVERSION.src.tar.xz
             https://github.com/llvm/llvm-project/releases/download/llvmorg-$PKGVERSION/clang-tools-extra-$PKGVERSION.src.tar.xz"
PKGDEPENDS="dev/cmake:build"
PKGOPTIONS="COMPILER_RT LIBCXX LLD TOOLS"

: ${CC:=clang}
: ${CFLAGS:=-O2}
: ${CXX:=clang++}
: ${CXXFLAGS:=-O2}
: ${COMPILER_RT:=yes}
: ${LIBCXX:=yes}
: ${LLD:=yes}
: ${TOOLS:=yes}

if [ "$COMPILER_RT" = "yes" ]; then
	with_compiler_rt="-DCLANG_DEFAULT_RTLIB=compiler-rt"
fi

if [ "$LIBCXX" = "yes" ]; then
	with_libcxx="-DCLANG_DEFAULT_CXX_STDLIB=libc++"
else
	with_libcxx="-DCLANG_DEFAULT_CXX_STDLIB=libstdc++"
fi

if [ "$LLD" = "yes" ]; then
	with_lld="-DCLANG_DEFAULT_LINKER=lld"
fi

build()
{
	rm -rf cfe-$PKGVERSION.src
	tar xvf cfe-$PKGVERSION.src.tar.xz
	cd cfe-$PKGVERSION.src

	# Extract clang-extra-tools as tools/extra if requested.
	if [ "$TOOLS" = "yes" ]; then
		tar xvf ../clang-tools-extra-$PKGVERSION.src.tar.xz -C tools
		mv tools/clang-tools-extra-$PKGVERSION.src tools/extra
	fi

	patch -p0 < ../patch-musl.patch
	mkdir build && cd build
	cmake .. -Wno-dev \
		-DCMAKE_BUILD_TYPE=Release \
		-DCMAKE_CXX_COMPILER="$CXX" \
		-DCMAKE_CXX_FLAGS="$CXXFLAGS" \
		-DCMAKE_C_COMPILER="$CC" \
		-DCMAKE_C_FLAGS="$CFLAGS" \
		-DCMAKE_INSTALL_PREFIX= \
		-DCMAKE_INSTALL_MANDIR=/share/man \
		-DCLANG_VENDOR="Vanilla Linux" \
		-DLLVM_ENABLE_EH=On \
		-DLLVM_ENABLE_RTTI=On \
		$with_compiler_rt \
		$with_libcxx \
		$with_lld
	make
	make DESTDIR=$DESTDIR install
	# Compatibility symlink for many autotools programs.
	ln -sf $DESTDIR/bin/clang-cpp $DESTDIR/bin/cpp
	cd ..

	cd ..
	rm -rf cfe-$PKGVERSION.src
}
