#!/bin/sh

set -e

log() {
	printf '%s' "${@}" >&2
}

logl() {
	printf '%s\n' "${@}" >&2
}

checkprefix() {
	logl "irctk will be installed in...${PREFIX:-/usr/local}"
}

checkman() {
	log 'checking manpage version...'
	case $(uname) in
	OpenBSD)
		M4MANVER=mdoc
		;;
	esac
	logl "${M4MANVER}"
}

checktclsh() {
	log 'checking tclsh interpreter...'
	if [ -z "${TCLSH}" ]; then
		set +e
		if which tclsh8.6 2>/dev/null >/dev/null; then
			TCLSH=tclsh8.6
		elif which tclsh9.0 2>/dev/null >/dev/null; then
			TCLSH=tclsh9.0
		else
			set -e
			logl 'not found'
			logl 'error: could not find tclsh'
			return 1
		fi
		export TCLSH
		set -e
	fi
	logl ${TCLSH}
	return 0
}

help() {
	logl 'usage: configure [-h] [-p prefix] [-t tclsh]'
	logl ''
	logl 'command line options'
	logl ' '
	logl '	-h	show this help message'
	logl '	-p	set the installation prefix, override PREFIX'
	logl '	-t	set the tclsh interpreter to use, override TCLSH'
	logl ' '
	logl 'environment variables'
	logl ''
	logl '	PREFIX	Installation prefix path'
	logl '	TCLSH	tclsh shell'
}

while getopts 'hp:t:' _flag; do
	case ${_flag} in
	h)
		help
		exit 0
		;;
	p)
		PREFIX=${OPTARG}
		export PREFIX
		;;
	t)
		TCLSH=${OPTARG}
		export TCLSH
		;;
	?)
		exit 1
		;;
	esac
done

shift $((OPTIND-1))

# Checks

checkprefix
checktclsh
checkman

# Building the final makefile

log 'generating makefile...'
m4 -DM4PREFIX=${PREFIX:-/usr/local} -DM4TCLSH=${TCLSH} \
    -DM4MANVER=${M4MANVER:-man} Makefile.m4 >Makefile
logl 'done'
