#!/bin/sh
#
# Copyright (C)2026 kimapr
#
# This file is part of fcnatfw.
#
# fcnatfw is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# fcnatfw is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <https://www.gnu.org/licenses/>.
#


if ! test -f Makefile; then
	echo VPATH builds not supported >&2
	exit 1
fi

CC_set=""

for arg; do
	case "$arg" in
		--prefix=*) prefix="${arg#*=}";
			printf 'prefix=%s\n' "$prefix";;
		--exec-prefix=*) exec_prefix="${arg#*=}";
			printf 'exec_prefix=%s\n' "$exec_prefix";;
		--bindir=*) bindir="${arg#*=}";
			printf 'bindir=%s\n' "$bindir";;
		--libdir=*) libdir="${arg#*=}";
			printf 'libdir=%s\n' "$libdir";;
		-*) :;;
		CC=*) CC_set=1; printf '%s\n' "$arg";;
		*) printf '%s\n' "$arg";;
	esac
done > config.mk

test -z "$prefix" && prefix="/usr/local"
test -z "$exec_prefix" && exec_prefix="$prefix"
test -z "$bindir" && bindir="$exec_prefix/bin"
test -z "$libdir" && libdir="$exec_prefix/lib"

if test -z "$CC_set"; then
	{
		printf 'CC=';
		{ test -n "$CC" && printf '%s' "$CC"; } ||
		command -v cc ||
		command -v gcc ||
		command -v clang ||
		{ printf 'No C compiler found.\n' >&2; exit 1; }
		printf '\n'
	} >> config.mk
fi

{
	printf 'FCNATFW_INSTALLED=1\n'
	printf "FCNATFW_LIBDIR=%$(if [ "x$BASH_VERSION" = x ]; then printf s; else printf q; fi)\\n" "$libdir"
	wrap_command() {
		if test -z "$2"; then
			if ! command -v "$1" >/dev/null; then
				return 1;
			fi
			if ! test "$(command -v "$1" | head -c1)" = "/"; then
				return;
			fi
		fi
		printf '%s() { %s "$@"; }\n' "$1" "$( (if test -z "$2"; then
			command -v "$1"
		else
			printf '%s' "$2"
		fi) | sed 's|[^a-zA-Z0-9._=/-]|\\\0|g')"
	}
	for cmd in ncat stunclient grep sed head realpath dirname sleep bash; do
		wrap_command "$cmd" || { printf 'Required executable not found: %s.\n' "$cmd" >&2; exit 1; }
	done
	wrap_command fcnatwrap "$bindir/fcnatwrap"
	printf 'wrapper=fcnatwrap\n'
	wrap_command upnpc
} > bin/prelude

{
	command -v bash || { printf 'Bash not found.\n' >&2; exit 1; }
} > bin/interpreter

{
	printf './configure'
	for arg; do
		printf ' '
		printf '%s' "$arg" | sed 's|[^a-zA-Z0-9._=/-]|\\\0|g'
	done
	echo
} > config.status

chmod +x config.status
