#!/usr/bin/env modbuild

# :FIXME: need review!

CCTOOLS_VERSION='895'
DYLD_VERSION='421.2'

SOURCE_URL="http://opensource.apple.com/tarballs/$P/$P-$V.tar.gz"
CCTOOLS_SOURCE_URL="https://opensource.apple.com/tarballs/cctools/cctools-${CCTOOLS_VERSION}.tar.gz"
DYLD_SOURCE_URL="http://opensource.apple.com/tarballs/dyld/dyld-${DYLD_VERSION}.tar.gz"


pbuild::patch_sources () {
	find_patchdir() {
		local -a patchdirs=()
		patchdirs+=( "${BUILDBLOCK_DIR}/${V}/patches.${OS}" )
		patchdirs+=( "${BUILDBLOCK_DIR}/${V}/patches" )
		patchdirs+=( "${BUILDBLOCK_DIR}/${V%.*}/patches.${OS}" )
		patchdirs+=( "${BUILDBLOCK_DIR}/${V%.*}/patches" )
		patchdirs+=( "${BUILDBLOCK_DIR}/${V%.*.*}/patches.${OS}" )
		patchdirs+=( "${BUILDBLOCK_DIR}/${V%.*.*}/patches" )

		for patchdir in "${patchdirs[@]}"; do
			 [[ -e "${patchdir}" ]] && return 0;
		done
		return 1
	}

	find_patchdir || return 0
	local patch_file=''
	for patch_file in "${patchdir}"/*; do
		patch -p0 < "${patch_file}"
	done
}

pbuild::post_prep() {
	local -r DYLD_SRC_DIR="${TEMP_DIR}/dyld-${DYLD_VERSION}/src"
	local -r CCTOOLS_SRC_DIR="${TEMP_DIR}/cctools-${CCTOOLS_VERSION}/src"

        local source_file=''
        pbuild::get_source source_file "${DYLD_SOURCE_URL}" "${PMODULES_DISTFILESDIR}" ||
                std::die 4 "dyld/${DYLD_VERSION}: sourcecode not found."
        pbuild::unpack "${source_file}" "${DYLD_SRC_DIR}" 
	
        pbuild::get_source source_file "${CCTOOLS_SOURCE_URL}" "${PMODULES_DISTFILESDIR}" ||
                std::die 4 "cctools/${CCTOOLS_VERSION}: sourcecode not found."
        pbuild::unpack "${source_file}" "${CCTOOLS_SRC_DIR}"

	cd "${SRC_DIR}"
	mkdir -p "include/mach-o"
	rsync --archive "../../cctools-${CCTOOLS_VERSION}/src/include/mach-o/" "include/mach-o/"
	rsync --archive "../../dyld-${DYLD_VERSION}/src/include/mach-o/" "include/mach-o/"
	mkdir -p "include/llvm-c"
	cp -v "${BUILDBLOCK_DIR}/files/Disassembler.h" "include/llvm-c/"
	cp -v "${BUILDBLOCK_DIR}/files/lto.h" "include/llvm-c/"
}

pbuild::configure() {
	cp -v "${BUILDBLOCK_DIR}/files/Makefile-${V_MAJOR}" "${SRC_DIR}/Makefile"
}

pbuild::compile() {
	cd "${SRC_DIR}"
	which $CC
	make OTHER_CXXFLAGS="-std=c++11 -I$PWD/include" OTHER_LDFLAGS="-L/Applications/Xcode.app/Contents/Frameworks -lLTO"
}

# use system gcc to compile
declare -rx CC=/usr/bin/gcc
declare -rx CXX=/usr/bin/g++

pbuild::add_to_group 'Programming'
pbuild::install_docfiles 'COPYING' 'COPYING.LIB' 'COPYING.RUNTIME' 'COPYING3' 'COPYING3.LIB' 'NEWS' 'README'
pbuild::make_all

