#!/bin/bash
set -e
set -x
tag="$1"; shift
[ -n "$tag" ] || exit 1
sw="$1"; shift || true
[ -n "$sw" ] || sw="$tag"

IDIR="$PWD"
ZIPNAME="${sw}-win32"
OUTDIR="$PWD/w32zip/$ZIPNAME"
TMPDIR="${OUTDIR}-tmp"

set -e
mkdir -v "$OUTDIR"
dlls='
	pdcurses.dll
	libcurl-4.dll
	pthreadGC2.dll
	libjansson-4.dll
	libusb-1.0.dll
	zlib1.dll
'
cp -v \
	-L \
	$dlls \
	"$OUTDIR/"
for dll in $dlls; do
	i686-pc-mingw32-strip "$OUTDIR/$dll"
done
git branch TMP "$tag"
git clone . "$TMPDIR" -b TMP --depth 1
git branch -D TMP
cd "$TMPDIR"
git submodule update --init
git archive --prefix "$sw"/ --format tar "$tag" | tar xvp
(
	cd libblkmaker
	git archive --prefix "libblkmaker/" --format tar HEAD | tar -C "../$sw" -xvp
)
cd "$sw"
NOSUBMODULES=1 \
NOCONFIGURE=1 \
./autogen.sh
cd ..
zip -r "$IDIR/${sw}.zip" "$sw"
tar cjvpf "$IDIR/${sw}.tbz2" "$sw"
SRCDIR="$TMPDIR/$sw"
for txt in AUTHORS COPYING NEWS README API-README FPGA-README SCRYPT-README; do
	sed 's/$/\r/' <"$txt" >"$OUTDIR/${txt}.txt"
done
cp -av "bitstreams" "$OUTDIR/"
NOCONFIGURE=1 \
./autogen.sh
./configure \
	--prefix='C:\\Program Files\\BFGMiner\' \
	CFLAGS='-march=i686 -Wall' \
	--disable-cpumining \
	--enable-opencl \
	--enable-adl \
	--enable-bitforce \
	--enable-icarus \
	--enable-modminer \
	--enable-ztex \
	--enable-scrypt \
	--build=i686-pc-linux-gnu \
	--host=i686-pc-mingw32
make -j4
i686-pc-mingw32-strip \
	libblkmaker/.libs/*.dll \
	bfgminer.exe
cp -v \
	bfgminer.exe \
	libblkmaker/.libs/*.dll \
	*.cl \
	example.conf \
	windows-build.txt \
	API.class \
	miner.php \
	"$OUTDIR/" -v
cd "$OUTDIR"
cd ..
zip -r "$IDIR/${ZIPNAME}.zip" "${ZIPNAME}"
cd "$IDIR"
