_targets="i686-w64-mingw32 x86_64-w64-mingw32"

# Phase 1. headers

for _target in ${_targets}; do
    abinfo "Configuring ${_target} ..."
    mkdir $SRCDIR/header-build-${_target} && cd $SRCDIR/header-build-${_target}
    $SRCDIR/mingw-w64-headers/configure \
        --prefix=/opt/w64/${_target} --enable-sdk=all --enable-secure-api \
        --host=${_target} CC=${_target}-gcc CXX=${_target}-g++

    abinfo "Building ${_target} headers ..."
    make

    abinfo "Installing ${_target} headers ..."
    make install DESTDIR=$PKGDIR
done

# Phase 2. C Runtime

for _target in ${_targets}; do
    abinfo "Configuring ${_target} runtime ..."
    if [ ${_target} == "i686-w64-mingw32" ]; then
        _crt_configure_args="--disable-lib64 --enable-lib32"
    elif [ ${_target} == "x86_64-w64-mingw32" ]; then
        _crt_configure_args="--disable-lib32 --enable-lib64"
    fi
    mkdir $SRCDIR/rt-build-${_target} && cd $SRCDIR/rt-build-${_target}

    headers="$PKGDIR"/opt/w64/${_target}/include
    $SRCDIR/mingw-w64-crt/configure --prefix=/opt/w64/${_target} \
        --host=${_target} --enable-wildcard \
        ${_crt_configure_args} \
        CC=${_target}-gcc CXX=${_target}-g++ \
        CFLAGS="$CFLAGS -I${headers}" \
        CXXFLAGS="$CXXFLAGS -I${headers}"

    abinfo "Building ${_target} runtime ..."
    make

    abinfo "Installing ${_target} runtime ..."
    make install DESTDIR=$PKGDIR
done

# Phase 3. Win Pthread

for _target in ${_targets}; do
    abinfo "Configuring ${_target} win pthread ..."
    mkdir $SRCDIR/pth-build-${_target} && cd $SRCDIR/pth-build-${_target}
    $SRCDIR/mingw-w64-libraries/winpthreads/configure \
        --prefix=/opt/w64/${_target} \
        --host=${_target} --enable-static \
        --enable-shared CC=${_target}-gcc CXX=${_target}-g++

    abinfo "Building ${_target} win pthread ..."
    make

    abinfo "Installing ${_target} win pthread ..."
    make install DESTDIR=$PKGDIR
    ${_target}-strip --strip-unneeded $PKGDIR/opt/w64/${_target}/bin/*.dll
done

cd $SRCDIR
