#!/bin/bash

OPENSSL_VERSION=3.3.1

API_LEVEL=24

BUILD_DIR=out/openssl_mingw64_build

BUILD_TARGETS="mingw64"

WORK_DIR=out/openssl-${OPENSSL_VERSION}-mingw64
rm -rf $WORK_DIR
cp -arf deps/openssl_src/ $WORK_DIR

build_the_thing() {
    export GLOBAL_OPTIONS="no-trace no-asm no-threads no-md2 no-md4 no-dso no-async no-multiblock no-dgram no-filenames no-shared no-ssl3 no-engine no-dynamic-engine no-zlib no-comp no-psk no-idea no-srp no-weak-ssl-ciphers no-dtls no-egd no-tests -Os"
    echo "./Configure $SSL_TARGET $OPTIONS $GLOBAL_OPTIONS" && \
    ./Configure $SSL_TARGET $OPTIONS $GLOBAL_OPTIONS && \
    make clean && \
    make build_generated && \
    make libcrypto.a libssl.a || exit 128
}

for build_target in $BUILD_TARGETS
do
    echo "Building $build_target"
    pushd $WORK_DIR || exit 128

    case $build_target in
    mingw64)
        OPTIONS="--cross-compile-prefix=x86_64-w64-mingw32-"
        DESTDIR="/tmp/$BUILD_DIR/mingw64"
        SSL_TARGET="mingw64"
    ;;
    esac

    rm -rf $DESTDIR
    build_the_thing
    popd
    echo WORK_DIR=$WORK_DIR
    rm -rf deps/openssl/$build_target/
    mkdir -p deps/openssl/$build_target/usr/local/include/
    mkdir -p deps/openssl/$build_target/usr/local/lib/
    cp -R $WORK_DIR/include/* deps/openssl/$build_target/usr/local/include/
    cp $WORK_DIR/*.a deps/openssl/$build_target/usr/local/lib/
done

echo Success