#!/bin/sh
# $Id: build-vile,v 1.13 2020/01/06 00:38:56 tom Exp $
# vile:ts=4 sw=4
THIS=vile

clean-$THIS || exit 1

. no-rcs

clean() {
	( clean-$THIS; rm -f *.out )
}

buildit() {
	rcs_save

	mkdir -p BUILD_dir
	trap 'rc=$?; rm -rf $BUILD_DIR; rcs_restore; exit $rc' EXIT INT QUIT TERM

	test -d LOGS  || mkdir LOGS
	if ln -f run.log LOGS/run.log
	then
		:
	else
		mv run.log LOGS/
	fi

	appsdir=$BUILD_DIR/etc/X11/app-defaults
	mkdir -p $appsdir

	icondir=$BUILD_DIR/usr/share/icons
	mkdir -p $icondir

	pixmapdir=$BUILD_DIR/usr/share/pixmaps
	mkdir -p $pixmapdir

	TARGET=$1
	ACTUAL=$2
	shift 2
	echo "BUILD_DIR $TARGET: $*"
	test -f bin/$TARGET || ( ( \
		"$@" && \
		make-out $TARGET$x && \
		make-out install   prefix=$BUILD_DIR appsdir=$appsdir icondir=$icondir pixmapdir=$pixmapdir && \
		make-out uninstall prefix=$BUILD_DIR appsdir=$appsdir icondir=$icondir pixmapdir=$pixmapdir && \
		cp $TARGET bin/$ACTUAL && \
		make distclean ) ) || exit

	rm -rf $BUILD_DIR
}

savelog() {
	echo "..savelog $BUILD_LOG"
	if test -f LOGS/run.log
	then
		sed -e s%$BUILD_DIR%BUILD%g -e s%`pwd`%SRCDIR%g LOGS/run.log >$BUILD_LOG
		rm -f LOGS/run.log
	fi
	ls -l LOGS
}

if test -z "$BUILD_LOG" ; then
	clean

	mkdir -p LOGS

	BUILD_DIR=`unset CDPATH; pwd`/BUILD_dir
	export BUILD_DIR

	BUILD_CC=`echo "$CC" | sed -e 's, .*,,' -e 's,^.*/,,'`
	test "$BUILD_CC" = "gcc" && BUILD_CC=
	test -n "$BUILD_CC" && BUILD_CC="$BUILD_CC-"

	BUILD_LOG=LOGS/`partition`-${BUILD_CC-cc}run.log
	BUILD_LOG=run.log run-log $0
	rm -f run.log

	savelog

else
	x=
	case `partition` in #(vi
	cygwin*)
		x=".exe"
		;;
	*netbsd*|par-dgfly210-32)
		. with-pkgsrc
		;;
	esac

	rm -rf bin
	mkdir bin

	buildit x$THIS x$THIS cfg-kev-x$THIS "$@"
	buildit $THIS  $THIS  cfg-$THIS "$@"
fi
