#!/bin/sh
# configure, make and install a program from source
# (c) 2007..2008 by Dirk Jagdmann <doj@cubic.org>

if [ "$1" = "-h" -o "$1" = "--help" ] ; then
    echo "usage: cmi [archive name]"
    exit 1
fi

if [ -f "$1" ] ; then

    if [ `which deco 2>/dev/null` ] ; then
	BASE=`deco "$1"`
	cd "$BASE"
    else
	TARBZ2=`basename "$1" .tar.bz2`
	TARGZ=`basename "$1" .tar.gz`
	TGZ=`basename "$1" .tgz`
	if [ "$1" = "$TARBZ2.tar.bz2" ] ; then
	    echo found tar.bz2
	    tar xfj "$1" || exit 1
	    BASE="$TARBZ2"
	elif [ "$1" = "$TARGZ.tar.gz" ] ; then
	    echo found tar.gz
	    tar xfz "$1" || exit 1
	    BASE="$TARGZ"
	elif [ "$1" = "$TGZ.tgz" ] ; then
	    echo found tgz
	    tar xfz "$1" || exit 1
	    BASE="$TGZ"
	fi

	if [ -d "$BASE" ] ; then
	    cd "$BASE"
	else
	    echo "don't know where $1 was extracted to"
	    exit 1
	fi
    fi
fi

if [ ! -f Makefile -a ! -f GNUMakefile -a ! -f BSDMakefile -a ! -f makefile ] ; then

    if [ -f Makefile.PL ] ; then
	perl Makefile.PL || exit 1

    elif [ -f configure ] ; then
	sh configure || exit 1

    elif [ -f autogen.sh ] ; then
	sh autogen.sh || exit 1
	sh configure || exit 1
    else
	echo "did not find configure, autogen.sh, Makefile.PL"
	exit 1
    fi

fi

make -j2 || exit 1
make install || exit 1
ldconfig

if [ "$BASE" ] ; then
    cd ..
    rm -rf "$BASE"
fi
