#!/bin/bash

API_LEVEL=24

BUILD_DIR=out/openssl_mingw64_build

BUILD_TARGETS="mingw64"

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

build_the_thing() {
    export GLOBAL_OPTIONS="
        no-apps
        no-asm
        no-async
        no-autoerrinit
        no-cmp
        no-cms
        no-comp
        no-deprecated
        no-dgram
        no-docs
        no-dsa
        no-dso
        no-dtls
        no-dynamic-engine
        no-ec2m
        no-egd
        no-engine
        no-err
        no-filenames
        no-gost
        no-http
        no-idea
        no-legacy
        no-md2
        no-md4
        no-module
        no-multiblock
        no-nextprotoneg
        no-ocsp
        no-psk
        no-shared
        no-sock
        no-srp
        no-ssl-trace
        no-ssl3
        no-stdio
        no-tests
        no-thread-pool
        no-threads
        no-trace
        no-ui-console
        no-uplink
        no-weak-ssl-ciphers
        no-zlib
        -Os
        -ffunction-sections
        -fdata-sections
        -flto
        -DOPENSSL_SMALL_FOOTPRINT"
    echo "./Configure $SSL_TARGET $OPTIONS $GLOBAL_OPTIONS" && \
    ./Configure $SSL_TARGET $OPTIONS $GLOBAL_OPTIONS && \
    make -s clean && \
    make -s build_generated && \
    make -s 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