#!/bin/bash
[% c("var/set_default_env") -%]
distdir=/var/tmp/dist/[% project %]
mkdir -p /var/tmp/dist
tar -C /var/tmp/dist -xf [% c('input_files_by_name/cmake') %]
tar -C /var/tmp/dist -xf [% c('input_files_by_name/ninja') %]
export PATH="/var/tmp/dist/ninja:/var/tmp/dist/cmake/bin:$PATH"

[% pc(c('var/compiler'), 'var/setup', { compiler_tarfile => c('input_files_by_name/' _ c('var/compiler')) }) %]

tar -C /var/tmp/dist -xf [% c('input_files_by_name/binutils') %]
export PATH="/var/tmp/dist/binutils/bin:$PATH"

mkdir -p /var/tmp/build
cd /var/tmp/build
tar -xf $rootdir/[% c('input_files_by_name/clang-source') %]
cd clang-source
export LLVM_HOME=$(pwd)
mkdir build
cd build

installdir=/var/tmp/build/install
mkdir -p $installdir

cmake ../compiler-rt/ -GNinja \
  -DCMAKE_INSTALL_PREFIX=$installdir \
  -DCMAKE_BUILD_TYPE=Release \
  -DCMAKE_SYSTEM_NAME=Android \
  -DCMAKE_ANDROID_ARCH_ABI="[% c('var/abi') %]" \
  -DCMAKE_ANDROID_NDK="$ANDROID_NDK_HOME" \
  -DCMAKE_C_FLAGS="-fuse-ld=lld --rtlib=compiler-rt $defines" \
  -DCMAKE_CXX_FLAGS="-fuse-ld=lld --rtlib=compiler-rt $defines" \
  -DCMAKE_EXE_LINKER_FLAGS="-L$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/linux-x86_64/[% c('var/libdir') %]" \
  -DCOMPILER_RT_BUILD_BUILTINS=ON \
  -DCOMPILER_RT_BUILD_LIBFUZZER=OFF \
  -DCOMPILER_RT_BUILD_MEMPROF=OFF \
  -DCOMPILER_RT_BUILD_ORC=OFF \
  -DCOMPILER_RT_BUILD_PROFILE=OFF \
  -DCOMPILER_RT_BUILD_SANITIZERS=OFF \
  -DCOMPILER_RT_BUILD_XRAY=OFF

ninja -j[% c("num_procs") %] -v install

mkdir -p $distdir/lib/clang/[% c("var/llvm_version") %]/lib/linux/
mv $installdir/lib/linux/libclang_rt.builtins-*-android.a $distdir/lib/clang/[% c("var/llvm_version") %]/lib/linux/

cd /var/tmp/dist
[% c('tar', {
    tar_src => [ project ],
    tar_args => '-czf ' _ dest_dir _ '/' _ c('filename'),
  }) %]
