#!/bin/sh
# $Id: run-makensis,v 1.9 2018/01/05 01:04:58 tom Exp $
# vi:ts=4 sw=4

# http://nsis.sourceforge.net/Docs/

# Runs makensis on one or more scripts for the current BUILD-* directories,
# putting the result into ~/nsibuild

# We assume that the script is in a package (or PACKAGE) subdirectory, and
# that the BUILD-* are subdirectories also.  All source filenames in the
# script must be relative to the top-level directory, eliminating the need
# to adjust the script (makensis does have a -nocd option, but it is of little
# use).

TOP=`pwd`
for script in $*
do
	echo "** $script"
	if test ! -f "$script"
	then
		echo "... not a file"
		continue
	fi
	case "$script" in
	*.nsi|*.nsis)
		check=`basename $script`
		test "$check" = working.nsi && continue
		;;
	*)
		echo "... not a NSIS script"
		continue
		;;
	esac
	SCRIPT=`realpath $script`
	(
		cd $TOP
		cd `dirname $SCRIPT`
		cd ..
		for build in BUILD-*
		do
			case $build in
			*32)
				TARGET=$HOME/nsibuild/win32
				CHOOSE=`choose-mingw32`
				;;
			*64)
				TARGET=$HOME/nsibuild/win64
				CHOOSE=`choose-mingw64`
				;;
			*)
				echo "... ignored (expecting BUILD-W32 or BUILD-W64)"
				continue
				;;
			esac

			test -d "$build" && (
				cd $build
				# construct plain-text files for each manpage
				NO_MAN=`find . -type f -name '*.[1-9]'`
				if test -n "$NO_MAN"
				then
					echo "... construct plain-text documentation"
					for name in $NO_MAN
					do
						NAME=`echo "$name" | sed -e 's/\.1$/.txt/' -e 's/\.3$/-lib.txt/'`
						nroff -man "$name" | col -b >$NAME
					done
				fi
				# if I use AC_ARG_PROGRAM in the configure script, everything
				# gets installed using a cross-compiler prefix.  Make a copy
				# in the BUILD-Wxx tree without the prefix so that my ".nsi"
				# scripts can work.
				RENAME=`find . -type f -name "$CHOOSE*"`
				if test -n "$RENAME"
				then
					echo "... aliasing $CHOOSE-prefixed names"
					for name in $RENAME
					do
						NAME=`echo "$name" | sed -e "s/$CHOOSE-//"`
						ln -vf $name $NAME
					done
				fi
				find . -type f -ls
				OUTPUT=`grep 'OutFile' $SCRIPT | sed -e 's/^[^"]*"//' -e 's/\\\\.*//'`
				test -n "$OUTPUT" && (
					test -f working.nsi && rm -f working.nsi
					mkdir -p $OUTPUT
					echo "... building $build with $script"
					cp $SCRIPT working.nsi
					ls -l
					if ( makensis -v2 working.nsi )
					then
						ls -l $OUTPUT
						mkdir -p $TARGET
						mv -f $OUTPUT/* $TARGET/
						rmdir $OUTPUT
						rm -f working.nsi
					fi
				)
			)
		done
	)
done
