#!/bin/bash

# Setup script for pntools
# Author: Mohamed Bamakhrama (mohamed@liacs.nl)
# Copyrights (c) 2012, Leiden University. All rights reserved


##################################################################
# 
#  Packages
#
##################################################################

PN_DIR_NAME=pngen
ISA_PACKAGE_URL=http://daedalus.liacs.nl/pngen/release_20120706/setup_pngen.sh
ISA_DIR_NAME=isa-0.11-278-gad5ded6-snapshot

PNTOOLS_VERSION=0.1
PNTOOLS_PACKAGE_URL=http://daedalus.liacs.nl/pntools/release_20120711/pntools-$PNTOOLS_VERSION.zip
PNTOOLS_PACKAGE=`basename $PNTOOLS_PACKAGE_URL`
PNTOOLS_DIR_NAME=pntools-$PNTOOLS_VERSION

##################################################################
# 
#  Functions
#
##################################################################

# Takes two parameters. The response from a command and error message
# If the response is not zero, print the error message and exit
check() {
    if [ $1 -ne 0 ]
    then
        echo "ERROR: $2"
        exit 1
    fi
}

install_isa() {

	mkdir $PN_DIR_NAME
	mv setup_pngen.sh $PN_DIR_NAME/
	cd $PN_DIR_NAME

	chmod +x setup_pngen.sh	
	./setup_pngen.sh nocheck
	
	cd ..
}


install_pntools() {

    echo "unzip $PNTOOLS_PACKAGE"
    unzip $PNTOOLS_PACKAGE
    check $? "can not unzip $PNTOOLS_PACKAGE"
    
    echo "cd $PNTOOLS_DIR_NAME"
    cd $PNTOOLS_DIR_NAME
    echo './autogen.sh'
    ./autogen.sh
    check $? "problem encountered while executing ./autogen.sh"

    echo "./configure --with-pngen=$PN_PATH --with-isa=$PN_PATH/$ISA_DIR"
    ./configure --with-pngen=$PN_PATH --with-isa=$PN_PATH/$ISA_DIR
    check $? "problem encountered while executing ./configure"

    echo 'make'
    make
    check $? "problem encountered while executing make"

    echo "cd .."
    cd ..
}


#############################################################
#
# Start of the setup procedure
#
#############################################################

if [ "$1" = "clean" ] 
then
    rm -rf $PN_DIR_NAME
    rm -rf $PNTOOLS_DIR_NAME
    rm -rf $PNTOOLS_PACKAGE
    echo "All downloaded files removed"
    exit 0
fi

BASE_DIR=`pwd`

if [ -d "$1" ]
then
    echo "wget -q -nc $PNTOOLS_PACKAGE_URL"
    wget -q -nc $PNTOOLS_PACKAGE_URL
    check $? "can not wget -q pntools"
    
    PN_PATH=$1
    cd $PN_PATH
    ISA_DIR=`find . -maxdepth 1 -type d -name "isa*"  | xargs basename`
    check $? "Invalid pn directory specified"
    cd -
    
	install_pntools
else
    echo "wget -q -nc $ISA_PACKAGE_URL"
    wget -q -nc $ISA_PACKAGE_URL
    check $? "can not download isa installer"
    
    echo "wget -q -nc $PNTOOLS_PACKAGE_URL"
    wget -q -nc $PNTOOLS_PACKAGE_URL
    check $? "can not wget -q pntools"    
    
    PN_PATH=$BASE_DIR/$PN_DIR_NAME
    ISA_DIR=$ISA_DIR_NAME
    
	install_isa
	install_pntools
fi


echo 'pntools installed successfully!'
exit 0


