#!/bin/bash -e

# Script used for non-rpm install.

function usage {
    echo "Usage: $0 base-directory [ arguments to configure-agraph ... ]"
    exit 1
}

function get_answer {
    local var_to_set=$1
    local prompt="$2"
    local default=$3
    
    local res

    while [ -z "$res" ]; do
	if [ "$default" ]; then
	    echo -n "$prompt [$default]: "
	else
	    echo -n "$prompt: "
	fi
	read res
	
	if [ -z "$res" ]; then
	    if [ "$default" ]; then
		res=$default
	    else 
		echo "This question requires a non-blank answer."
	    fi
	fi
    done

    eval $var_to_set=$res
}

function y_or_n {
    local prompt="$1"
    local default=$2

    while true; do
	get_answer y_or_n "$prompt" $default
	case "$y_or_n" in
	    y)
		return 0
		;;
	    n)
		return 1
		;;
	    *)
		echo Please answer either y or n
		;;
	esac
    done
}

if [ `arch` != x86_64 ]; then
    echo AllegroGraph Server requires 64-bit Linux
    exit 1
fi

if [ $# -lt 1 ]; then
    usage
fi

basedir="${1%/}"
srcdir="`dirname $0`"

if [ -d $basedir ]; then
    echo "$basedir already exists."
    if ! y_or_n "Overwrite? (config files will not be affected)" "n"; then
	    echo Aborting.
	    exit 1
    fi
fi

mkdir -p "$basedir"/{lib,bin,log,data}
mkdir -p "$basedir"/data/{settings,rootcatalog}
cp -pr $srcdir/* "$basedir"/lib
# Try to setup selinux.  
semanage fcontext -a -t textrel_shlib_t "$basedir/lib"'/libacl.*\.so' >/dev/null 2>&1 || :
chcon -t textrel_shlib_t "$basedir/lib"/libacl*.so >/dev/null 2>&1 || :

rm "$basedir"/lib/install-agraph

for prg in {agraph,agraph-control,agraph-backup,agraph-restore,agraph-recover,agraph-replicate,ag3-export,ag4-import,agload}; do
    rm -f "$basedir"/bin/$prg
    ln -s ../lib/$prg "$basedir"/bin/$prg
done
rm -f "$basedir"/doc
ln -s lib/doc "$basedir"/doc

echo Installation complete.

cfgfile="$basedir/etc/agraph.cfg"
if [ -f "$cfgfile" ]; then
    echo $cfgfile already exists.  Not running configuration script.
else
    echo Now running configure-agraph...
    shift
    "$basedir/lib/configure-agraph" "$@"
fi
