#!/bin/bash
#set -x
#Error checking
if [ ! -n "$1" ]
then
    echo "Please pass the base dir and re-run script"
    exit 1
fi
 
base_dir="$1/Tools"
 
gnum4_path="$base_dir/GNUM4"
autoconf_path="$base_dir/Autoconf"
automake_path="$base_dir/Automake"
libtool_path="$base_dir/Libtool"
 
install_dir="$base_dir/install-dir"
 
gnum4_version="m4-1.4.17"
autoconf_version="autoconf-2.69"
automake_version="automake-1.15"
libtool_version="libtool-2.4.6"
 
gnum4_repo="http://ftp.gnu.org/gnu/m4/$gnum4_version.tar.gz"
autoconf_repo="http://ftp.gnu.org/gnu/autoconf/$autoconf_version.tar.gz"
automake_repo="http://ftp.gnu.org/gnu/automake/$automake_version.tar.gz"
libtool_repo="https://ftp.gnu.org/gnu/libtool/$libtool_version.tar.gz"
 
error_print()
{
    step=$1
    repo_name=$2
    err_code=$3
    if [ "$err_code" -ne "0" ]
    then
            echo "$step for $repo_name failed"
            cd -
            exit 1
    else
        if [ "$VERBOSE" == "1" ]
        then
                echo "$step for $repo_name succeeded"
       fi
    fi
}
 
install_library()
{
    repo=$1
    repo_name=$2
    local_path=$3
 
    cd $local_path
    wget $repo >& /dev/null
    error_print "wget" $repo_name $?
 
    tar -zxvf "$repo_name.tar.gz"  >& /dev/null
    error_print "un-tar" $repo_name $?
 
    cd $repo_name
 
    ./configure --prefix=$install_dir >& /dev/null
    error_print "configure" $repo_name $?
 
    make clean &> /dev/null
    error_print "make clean" $repo_name $?
 
    make &> /dev/null
    error_print "make" $repo_name $?
 
    make install &> /dev/null
    error_print "make install" $repo_name $?
 
    cd - >& /dev/null
}
 
mkdir -p $gnum4_path $autoconf_path $automake_path $libtool_path $install_dir
 
#Install GNU M4
install_library $gnum4_repo $gnum4_version $gnum4_path echo "$gnum4_version installed successfully"
 
#Install Autoconf
install_library $autoconf_repo $autoconf_version $autoconf_path echo "$autoconf_version installed successfully"
 
#Install Libtool
install_library $libtool_repo $libtool_version $libtool_path echo "$libtool_version installed successfully"
 
#Install Automake
install_library $automake_repo $automake_version $automake_path echo "$automake_version installed successfully"

