set -x

FCC_ROOT=$1
if [ -z "$FCC_ROOT" ]; then
    echo "FCC_ROOT not set. Aborting!"
    exit 1
fi

ARCH=$2
if [ -z "$ARCH" ]; then
    echo "ARCH not set. Aborting!"
    exit 1
fi

CURL_VERSION=$3
if [ -z "$CURL_VERSION" ]; then
    echo "CURL_VERSION not set. Aborting!"
    exit 1
fi

source $FCC_ROOT/build_env/osx/osx_defs.sh


PLATFORM="MacOSX"

#
#       Note valid archs are i386 (for iPhoneSimulator) armv7 armv7s ... (for devices)
#

if [[ ${ARCH} == arm64* ]] ;
then
    HOST_ARCH=aarch64-apple-darwin
else
#
# --host=arm64-apple-darwin is not yet supported by autoconf scripts, several posts claim that someting like arm??-apple-darwin will work
#
    HOST_ARCH=${ARCH}-apple-darwin
fi



FVW_CURL_ROOT=$FCC_ROOT/fvwcurl

TEMP_DIR=$FVW_CURL_ROOT/tmp/osx
TEMP_INST=$TEMP_DIR/inst
rm -rf $TEMP_INST
mkdir -p $TEMP_INST

cd $TEMP_DIR

# prepare sources
echo "preparing sources ..."
rm -rf curl-${CURL_VERSION}
tar xvzf $FVW_CURL_ROOT/curl-${CURL_VERSION}.tar.gz

cd curl-${CURL_VERSION}

#
# patch http.c to strip Transfer-Encoding and Content-Type header from CONNECT requests 
# (causes some proxies to wait for data before completing connect to destination)
#
patch ${TEMP_DIR}/curl-${CURL_VERSION}/lib/http.c $FVW_CURL_ROOT/build/patches/${CURL_VERSION}/http.c.patch


OSX_SDK=`xcrun --sdk macosx --show-sdk-path`
export CC=$(xcrun --find --sdk "${OSX_SDK}" clang)
export CXX=$(xcrun --find --sdk "${OSX_SDK}" clang++)
export CPP=$(xcrun --find --sdk "${OSX_SDK}" cpp)

export MACOSX_DEPLOYMENT_TARGET="$MIN_SDK_VERSION"
export CFLAGS="-arch ${ARCH} -pipe -Os -gdwarf-2 -isysroot ${OSX_SDK}"
export LDFLAGS="-arch ${ARCH} -isysroot ${OSX_SDK}"


./configure --disable-shared --enable-static --disable-dependency-tracking --with-darwinssl --disable-ldap --disable-ldap --prefix=$TEMP_INST --host=${HOST_ARCH} --build x86_64

if [ $? -ne 0 ]
then
echo "configure failed"
exit
fi

make -j `sysctl -n hw.logicalcpu_max`
make install

rm -rf $FVW_CURL_ROOT/include/curl
mkdir -p $FVW_CURL_ROOT/include

cp -r $TEMP_INST/include/curl $FVW_CURL_ROOT/include/OSX

# currently we don't build debug versions of libcurl, so the release version is deployed also for debug builds
mkdir -p $FVW_CURL_ROOT/lib/OSX/${ARCH}
cp $TEMP_INST/lib/*.a $FVW_CURL_ROOT/lib/OSX/${ARCH}


