#!/bin/bash

log() {
	echo "[automagic] " $@
}

die() {
	log "Fatal: "$@
	exit 1
}

if [[ ! -d platform/unix ]]; then
	log "Can't find the 'plaform/unix' folder, make sure you run this from the root of the repository."
	exit 1
fi

AUTOHEADER=${AUTOHEADER:-$(which autoheader)}
AUTOCONF=${AUTOCONF:-$(which autoconf)}
LIBTOOLIZE=${LIBTOOLIZE:-$(which libtoolize)}
ACLOCAL=${ACLOCAL:-$(which aclocal)}
AUTOMAKE=${AUTOMAKE:-$(which automake)}

[[ -x ${AUTOHEADER} ]] || die "Could not find autoheader. Install autoconf."
[[ -x ${AUTOCONF} ]]   || die "Could not find autoconf."
[[ -x ${LIBTOOLIZE} ]] || die "Could not find libtoolize. Install libtool."
[[ -x ${ACLOCAL} ]]    || die "Could not find aclocal. Install automake."
[[ -x ${AUTOMAKE} ]]   || die "Could not find automake."

print_errors() {
	local output
	output="$("$@" 2>&1)" && return 0
	printf "%s\n" "$output"
	return 1
}

automagic() {
	log "Copying files..."
	cp platform/unix/configure.ac .
	cp platform/unix/Makefile.am .

	log "Running genmodules..."
	if ! print_errors bash platform/unix/genmodules "$1"; then
		echo "You should be doing this from the root directory of the project."
		exit 1
	fi

	log "Running autoheader..."
	print_errors ${AUTOHEADER} || return 1 # Gimmie config.h.in

	log "Running libtoolize..."
	print_errors ${LIBTOOLIZE} --force || return 1

	log "Running aclocal..."
	print_errors ${ACLOCAL} || return 1

	log "Running autoconf..."
	print_errors ${AUTOCONF} || return 1

	log "Running automake..."
	print_errors ${AUTOMAKE} -a || return 1
}

automagic "$@"

if [[ $? -eq 1 ]]; then
	log "Failed, sadface."
	log "This is generally a configuration error (I'm looking at you aclocal)"
	exit 1
else
	log "Success, carry on configuring."
fi
