#!/bin/bash -e

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

# define variables
C_PROJECT_NAME="MVMCoreUI"
PHONE_CONFIGURATION="Release"
BUILD_DIR=$(xcodebuild -showBuildSettings -project ./${C_PROJECT_NAME}.xcodeproj | grep -w -o 'BUILD_DIR = .*' | cut -d\  -f3-)
PHONE_ARCHIVE_PATH="${BUILD_DIR}/${PHONE_CONFIGURATION}-iphoneos/${C_PROJECT_NAME}.xcarchive"
SIMULATOR_CONFIGURATION="Debug"
SIMULATOR_ARCHIVE_PATH="${BUILD_DIR}/${SIMULATOR_CONFIGURATION}-iphonesimulator/${C_PROJECT_NAME}.xcarchive"
FRAMEWORKS_DIR=$BUILD_DIR/../../../Frameworks/MVMCoreUI
UNIVERSAL_OUTPUTFOLDER="${BUILD_DIR}/universal"

# Update to use .xcframework
sed -i '' 's|MVMCore.framework \*\/ = {isa.*};|MVMCore.xcframework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcframework; name = MVMCore.xcframework; path = ../SharedFrameworks/MVMCore.xcframework; sourceTree = "<group>"; };|g' ./MVMCoreUI.xcodeproj/project.pbxproj
sed -i '' 's/MVMCore.framework/MVMCore.xcframework/g' ./MVMCoreUI.xcodeproj/project.pbxproj

sed -i '' 's|VDS.framework \*\/ = {isa.*};|VDS.xcframework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcframework; name = VDS.xcframework; path = ../SharedFrameworks/VDS.xcframework; sourceTree = "<group>"; };|g' ./MVMCoreUI.xcodeproj/project.pbxproj
sed -i '' 's/VDS.framework/VDS.xcframework/g' ./MVMCoreUI.xcodeproj/project.pbxproj

sed -i '' "s|path = \.\.\/SharedFrameworks|path = ${FRAMEWORKS_DIR}|g" ./MVMCoreUI.xcodeproj/project.pbxproj

# Build device archive
xcodebuild archive \
 -scheme "${C_PROJECT_NAME}" \
 -configuration ${PHONE_CONFIGURATION} \
 -archivePath "${PHONE_ARCHIVE_PATH}" \
 -sdk iphoneos \
 -destination 'generic/platform=iOS' \
 -quiet \
 SKIP_INSTALL=NO \
 ONLY_ACTIVE_ARCH=NO \
 FRAMEWORK_SEARCH_PATHS="$FRAMEWORKS_DIR" \
 ALWAYS_SEARCH_USER_PATHS=true
 
# Build simulator archive
xcodebuild archive \
 -scheme "${C_PROJECT_NAME}" \
 -configuration ${SIMULATOR_CONFIGURATION} \
 -archivePath "${SIMULATOR_ARCHIVE_PATH}" \
 -sdk iphonesimulator \
 -destination 'generic/platform=iOS Simulator' \
 -quiet \
 SKIP_INSTALL=NO \
 ONLY_ACTIVE_ARCH=NO \
 FRAMEWORK_SEARCH_PATHS=$FRAMEWORKS_DIR \
 ALWAYS_SEARCH_USER_PATHS=true
 
mkdir -p "${UNIVERSAL_OUTPUTFOLDER}"

# Remove any existing xc framework.
rm -rf ${UNIVERSAL_OUTPUTFOLDER}/${C_PROJECT_NAME}.xcframework

# Create the xcframework in the universal output folder.
xcodebuild -create-xcframework \
 -framework "${PHONE_ARCHIVE_PATH}/Products/Library/Frameworks/${C_PROJECT_NAME}.framework" \
 -framework "${SIMULATOR_ARCHIVE_PATH}/Products/Library/Frameworks/${C_PROJECT_NAME}.framework" \
 -output ${UNIVERSAL_OUTPUTFOLDER}/${C_PROJECT_NAME}.xcframework

# Copy the dSYM file as well.
ditto "${PHONE_ARCHIVE_PATH}/dSYMs/${C_PROJECT_NAME}.framework.dSYM" "${UNIVERSAL_OUTPUTFOLDER}/${C_PROJECT_NAME}.xcframework.dSYM"
