#!/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"
cp -v \
	-L \
	pdcurses.dll \
	libcurl-4.dll \
	pthreadGC2.dll \
	libusb-1.0.dll \
	zlib1.dll \
	"$OUTDIR/"
git branch TMP "$tag"
git clone . "$TMPDIR" -b TMP --depth 1
git branch -D TMP
cd "$TMPDIR"
git archive --prefix "$sw"/ --format tar "$tag" | tar xvp
cd "$sw"
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
cp -v \
	bfgminer.exe \
	*.cl \
	example.conf \
	windows-build.txt \
	API.class \
	miner.php \
	"$OUTDIR/" -v
cd "$OUTDIR"
cd ..
zip -r "$IDIR/${ZIPNAME}.zip" "${ZIPNAME}"
cd "$IDIR"
