#! /usr/bin/env bash

outDir="$1"
outDir="${outDir:-/dev/null/null}"
outDir="$(cd "${outDir}" && pwd)" || exit 1

cd "$(dirname "${BASH_SOURCE[0]}")" || exit 1

CC='CL'
AR='false'
RANLIB='false'
TCLEXT_BUILD='shared'
TCLSH_PROG='tclsh'
CFLAGS='$(OPENSSL_CFLAGS)'
CPPFLAGS='$(OPENSSL_CPPFLAGS) -I$(OPENSSL_DIR)/include -I$(TCL_DIR)/include -DPACKAGE_VERSION="\\"$(PACKAGE_VERSION)\\""'
DEFS='-DUSE_TCL_STUBS=1'
EXTENSION_TARGET='tcltls.dll'
INSTALL='false'
INSTALL_DATA='false'
INSTALL_PROGRAM='false'
LDFLAGS=''
LIBS='$(OPENSSL_LIBS) $(TCL_DIR)/lib/libtclstub86.lib ws2_32.lib advapi32.lib crypt32.lib user32.lib'
PACKAGE_VERSION="$(awk -F, '/^AC_INIT/{ version = $2; gsub(/ /, "", version); gsub(/\)/, "", version); print version }' < ../configure.ac)"
SHOBJFLAGS=''
SHOBJLDFLAGS='-LD'
TCL_DEFS='-DUSE_TCL_STUBS=1'
TCL_PACKAGE_PATH=''
exec_prefix='/'
libdir='/lib'
prefix='/'
srcdir='..'
WEAKENSYMS='ECHO'
REMOVESYMS='ECHO'
GEN_DH_PARAMS_ARGS='fallback'

sedCommand=''
sedCommand+='s@\([[:space:]]\)mv @\1REN @g'$'\n'
sedCommand+='s@\([[:space:]]\)rm -f @\1DEL /F @g'$'\n'
sedCommand+='s@\([[:space:]]\)rm -rf @\1DEL /F @g'$'\n'
sedCommand+='s@\([[:space:]-]\)rmdir @\1DEL /F @g'$'\n'
sedCommand+='s@Makefile@Makefile.vc@g'$'\n'
sedCommand+='/DEL .*Makefile\.vc/ d'$'\n'
sedCommand+='/DEL .*dh_params\.h/ d'$'\n'
sedCommand+='/DEL .*tls\.tcl\.h/ d'$'\n'
for var in CC AR RANLIB CFLAGS CPPFLAGS DEFS EXTENSION_TARGET INSTALL INSTALL_DATA INSTALL_PROGRAM LDFLAGS LIBS PACKAGE_VERSION SHOBJFLAGS SHOBJLDFLAGS TCL_DEFS TCL_PACKAGE_PATH exec_prefix libdir prefix srcdir TCLEXT_BUILD WEAKENSYMS REMOVESYMS TCLSH_PROG GEN_DH_PARAMS_ARGS; do
	val="$(set | grep "^${var}=" | sed "s@^${var}=@@")"
	sedCommand+="s|@${var}@|$(eval echo ${val})|g"$'\n'
done
sedCommand+='/-o [^ ]*\.o/ s@ -o @ -Fo@g'$'\n'
sedCommand+='/-o .* -c / s@ -o @ -Fo@g'$'\n'
sedCommand+='/-o [^ ]*\.dll/ s@ -o @ -Fe@g'$'\n'
sedCommand+='/^[^ ]*.h:/,/^ *$/ d'$'\n'
sedCommand+='/test:/,/^ *$/ d'$'\n'
sedCommand+='/ECHO/ d'$'\n'

for file in Makefile.in pkgIndex.tcl.in; do
	echo "Processing $file"
	case "${file}" in
		Makefile.in)
			outFile='Makefile.vc'
			;;
		*)
			outFile="$(echo "${file}" | sed 's@\.in$@@')"
			;;
	esac

	outFile="${outDir}/${outFile}"
	sed "${sedCommand}" < "../${file}" > "${outFile}"
done

# Add some possible values to the Makefile
(
	echo '# Specify OpenSSL and Tcl parameters here'
	echo '# -----BEGIN MODIFICATIONS-----'
	echo 'OPENSSL_DIR        = c:/OpenSSL-Win64'
	echo 'OPENSSL_LIBS       = c:/OpenSSL-Win64/lib/VC/static/libssl64MT.lib c:/OpenSSL-Win64/lib/VC/static/libcrypto64MT.lib'
	echo 'OPENSSL_CPPFLAGS   = -DNO_SSL2 -DNO_SSL3'
	echo ''
	echo 'TCL_DIR            = c:/Tcl'
	echo '# -----END MODIFICATIONS-----'

	cat "${outDir}/Makefile.vc"
) > "${outDir}/Makefile.vc.new"
mv "${outDir}/Makefile.vc.new" "${outDir}/Makefile.vc"
