#!/bin/bash
source $ROOT_PATH/scripts/common.sh
cd tmp/openssl-openssl-$OPENSSL_VERSION || handle_error "Failed to change directory to openssl source"

echo "### Configure and Build OpenSSL for mac x64..."
./Configure darwin64-x86_64-cc no-shared no-dynamic-engine --prefix=$GITHUB_WORKSPACE/build/mac/x64 || handle_error "Failed to configure OpenSSL for mac x64"
make || handle_error "Failed to build OpenSSL for mac x64"
make install_sw || handle_error "Failed to install OpenSSL for mac x64"
make clean || handle_error "Failed to clean OpenSSL build for mac x64"

echo "### Configure and Build OpenSSL for mac arm64..."
./Configure darwin64-arm64-cc no-shared no-dynamic-engine --prefix=$GITHUB_WORKSPACE/build/mac/arm64 || handle_error "Failed to configure OpenSSL for mac arm64"
make || handle_error "Failed to build OpenSSL for mac arm64"
make install_sw || handle_error "Failed to install OpenSSL for mac arm64"
make clean || handle_error "Failed to clean OpenSSL build for mac arm64"

echo "### Configure and Build OpenSSL for mac universal..."
mkdir -p $GITHUB_WORKSPACE/build/mac/universal/lib || handle_error "Failed to create universal lib directory"
lipo -create -output $GITHUB_WORKSPACE/build/mac/universal/lib/libcrypto.a $GITHUB_WORKSPACE/build/mac/x64/lib/libcrypto.a $GITHUB_WORKSPACE/build/mac/arm64/lib/libcrypto.a || handle_error "Failed to create universal libcrypto.a"
lipo -create -output $GITHUB_WORKSPACE/build/mac/universal/lib/libssl.a $GITHUB_WORKSPACE/build/mac/x64/lib/libssl.a $GITHUB_WORKSPACE/build/mac/arm64/lib/libssl.a || handle_error "Failed to create universal libssl.a"
cp -r $GITHUB_WORKSPACE/build/mac/x64/include $GITHUB_WORKSPACE/build/mac/universal/ || handle_error "Failed to copy include files for universal build"
