#!/usr/bin/env bash
################################################################################
#  THIS FILE IS 100% GENERATED BY ZPROJECT; DO NOT EDIT EXCEPT EXPERIMENTALLY  #
#  Read the zproject/README.md for information about making permanent changes. #
################################################################################

set -e

function usage {
    echo "Usage ./build.sh [ iPhoneOS armv7 | iPhoneOS armv7s | iPhoneOS arm64 | iPhoneSimulator i386 | iPhoneSimulator x86_64 ]"
}

PLATFORM=$1
if [ -z PLATFORM ]; then
    usage
    exit 1
fi

if [[ $PLATFORM == "iPhoneOS" ]]; then
    SDK="iphoneos"
elif [[ $PLATFORM == "iPhoneSimulator" ]]; then
    SDK="iphonesimulator"
else
    echo "Unknown platform '$PLATFORM'"
    usage
    exit 1
fi

TARGET=$2
if [ -z $TARGET ]; then
    usage
    exit 1
fi

if [[ $TARGET == "x86_64" ]]; then
    HOST="i386"
elif [[ $TARGET == "arm64" ]]; then
    HOST="arm"
else
    HOST=$TARGET
fi

export SDK_VERSION=${SDK_VERSION:-"15.5"}

PLATFORM_PATH="/Applications/Xcode.app/Contents/Developer/Platforms"
TOOLCHAIN_PATH="/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin"
SYSROOT=$PLATFORM_PATH/$PLATFORM.platform/Developer/SDKs/$PLATFORM$SDK_VERSION.sdk
OUTPUT_DIR=output/$PLATFORM/$TARGET
PWD="$(pwd)"

export CC="$(xcrun -sdk $SDK -find clang)"
export CPP="$CC -E"
export AR="$(xcrun -sdk $SDK -find ar)"
export RANLIB="$(xcrun -sdk $SDK -find ranlib)"
export CFLAGS="-arch $TARGET -isysroot $SYSROOT -miphoneos-version-min=$SDK_VERSION -fembed-bitcode"
export CPPFLAGS="-arch $TARGET -isysroot $SYSROOT -miphoneos-version-min=$SDK_VERSION -fembed-bitcode"
export LDFLAGS="-arch $TARGET -isysroot $SYSROOT"

cd ../../
mkdir -p $OUTPUT_DIR
./autogen.sh
./configure --prefix="$PWD/$OUTPUT_DIR" --host=$HOST-apple-darwin
make
make install

echo "$PLATFORM $TARGET build successful"
################################################################################
#  THIS FILE IS 100% GENERATED BY ZPROJECT; DO NOT EDIT EXCEPT EXPERIMENTALLY  #
#  Read the zproject/README.md for information about making permanent changes. #
################################################################################
