#!/bin/sh

#
# Copyright (C) 2022-01-30  Julien BRUGUIER
# 
# This program 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.
# 
# This program 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 <http://www.gnu.org/licenses/>.
#

cd $(dirname $0)
init_autotools() {
# default arguments

ACLOCAL=aclocal
AUTOCONF=autoconf
AUTOHEADER=autoheader
AUTOMAKE=automake
LIBTOOLIZE=libtoolize

ACLOCAL_ARGS=""

if [ -f init_autotools.local ]; then
  chmod u+x init_autotools.local
  . ./init_autotools.local
fi

abort () {
    echo "$1 not found or command failed. Aborting!"
    exit 1
}

rm -rf autom4te.cache/
rm -f aclocal.m4 && touch aclocal.m4 && chmod +w aclocal.m4
$LIBTOOLIZE --force --copy --automake || abort "libtoolize"
$ACLOCAL $ACLOCAL_ARGS || abort "aclocal"
$AUTOHEADER || abort "autoheader"
$AUTOMAKE --add-missing --copy --gnu || abort "automake"
$AUTOCONF || abort "autoconf"
}
getopts :lcmsh O
shift

case $O in
	l)
		make -f Makefile.local "$@"
	;;
	c)
		init_autotools
	;;
	m)
		init_autotools
		./configure --prefix='/usr' "$@" && make -j && (make install || sudo make install || su -c "make install")
	;;
	s)
		init_autotools
		./configure --prefix='/usr' "$@" && make -j && (make install || sudo make install || su -c "make install")
	;;
	*)
		cat << EOM
$0 OPTION [ARGUMENTS]

Perform a common installation of the plugin:

-l: Local installation. Recommended for plugins specific to an application. Use the LOCAL PLUGIN directive to use it in applications.
-c: Custom auto-tools installation. Use the PLUGIN directive to use it in applications.
-m: Machine auto-tools installation. Recommended for generic plugins used with any Simple Virtual Machine installation. Use the MACHINE PLUGIN directive to use it in applications.
-s: System auto-tools installation. Recommended for generic plugins used with a Simple Virtual Machine installed at system level. Use the PLUGIN with absolute path to use it in applications.

With -l option, extra ARGUMENTS are passed to make.
Otherwise, extra ARGUMENTS are passed to the configure script.

-h: Display this help.

EOM
	;;
esac
