#!/bin/bash -e

unset TOOLCHAINS #Xcode 7.3 BUG FIX  http://stackoverflow.com/questions/36184930/xcodebuild-7-3-cant-enable-bitcode

# define output folder environment variable
C_PROJECT_NAME="MVMCoreUI"
PHONE_CONFIGURATION="Release"
SIMULATOR_CONFIGURATION="Debug"
BUILD_DIR=$(xcodebuild -showBuildSettings -project ./MVMCoreUI.xcodeproj | grep -w -o 'BUILD_DIR = .*' | cut -d\  -f3-)
SIMULATOR_LIBRARY_PATH="${BUILD_DIR}/${SIMULATOR_CONFIGURATION}-iphonesimulator/${C_PROJECT_NAME}.framework"
FRAMEWORKS_DIR=$BUILD_DIR/../../../Frameworks/MVMCoreUI
UNIVERSAL_OUTPUTFOLDER=${BUILD_DIR}/universal

# Step 1. Build Device and Simulator versions
xcodebuild -scheme "${C_PROJECT_NAME}" ONLY_ACTIVE_ARCH=NO -configuration ${PHONE_CONFIGURATION} -sdk iphoneos -archivePath "${BUILD_DIR}/${PHONE_CONFIGURATION}-iphoneos/${C_PROJECT_NAME}" archive SKIP_INSTALL=false FRAMEWORK_SEARCH_PATHS=$FRAMEWORKS_DIR ALWAYS_SEARCH_USER_PATHS=true

xcodebuild -target "${C_PROJECT_NAME}" ONLY_ACTIVE_ARCH=NO -configuration ${SIMULATOR_CONFIGURATION} -sdk iphonesimulator BUILD_DIR=$BUILD_DIR FRAMEWORK_SEARCH_PATHS=$FRAMEWORKS_DIR ALWAYS_SEARCH_USER_PATHS=true ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES=true

mkdir -p "${UNIVERSAL_OUTPUTFOLDER}"

rm -rf ${UNIVERSAL_OUTPUTFOLDER}/${C_PROJECT_NAME}.framework
cp -R "${BUILD_DIR}/${PHONE_CONFIGURATION}-iphoneos/${C_PROJECT_NAME}.xcarchive/Products/Library/Frameworks/${C_PROJECT_NAME}.framework" ${UNIVERSAL_OUTPUTFOLDER}

# Step 2. Create universal binary file using lipo

lipo -create -output "${UNIVERSAL_OUTPUTFOLDER}/${C_PROJECT_NAME}" "${UNIVERSAL_OUTPUTFOLDER}/${C_PROJECT_NAME}.framework/${C_PROJECT_NAME}" "${SIMULATOR_LIBRARY_PATH}/${C_PROJECT_NAME}"

mv ${UNIVERSAL_OUTPUTFOLDER}/${C_PROJECT_NAME} ${UNIVERSAL_OUTPUTFOLDER}/${C_PROJECT_NAME}.framework/${C_PROJECT_NAME}

# For Swift framework, Swiftmodule needs to be copied in the universal framework
if [ -d "${SIMULATOR_LIBRARY_PATH}/Modules/${C_PROJECT_NAME}.swiftmodule/" ]; then
    cp -a "${SIMULATOR_LIBRARY_PATH}/Modules/${C_PROJECT_NAME}.swiftmodule/" "${UNIVERSAL_OUTPUTFOLDER}/${C_PROJECT_NAME}.framework/Modules/${C_PROJECT_NAME}.swiftmodule/"
fi
