#! /bin/sh

# Create a new Pathena installation under user's ownership.
# This script first checks for suitable versions of required software,
# then starts up the PostgreSQL server, creates the initial Pathena
# database and launches the GUI client for the query interface.
# Default values are used throughout.  If customization is needed,
# read the file ~/.pathena/INSTALL.

# Home directory for Pathena files is changed in this script
# by invoking script 'build/relocate'.

export PATHENA=~/.pathena


# ---------------- Check for required software ----------------

echo "Checking for suitable versions of software that Pathena requires...
"

see_install="
Unfortunately, the quick installation procedure cannot be used.
See full installation instructions in file ~/.pathena/INSTALL.
"

MISSING=0

# Check for PostgreSQL in /usr/local/pgsql or system lib directories.

if $(/usr/local/pgsql/bin/pg_config --version &> /dev/null); then
     PGBIN=/usr/local/pgsql/bin
elif $(pg_config --version &> /dev/null); then
     PGBIN=$(pg_config --bindir)
else
     echo "PostgreSQL could not be found."
     MISSING=1
fi

# Check for Python and derive its version number.

if $(python -V &> /dev/null); then
     py_ver=$(python -c "import sys; print sys.version.split()[0]")
     py_ver2=$(python -c "import sys,re; print re.compile('(\d+\.\d+)').search(sys.version.split()[0]).group(0)")
else
     echo "Python could not be found."
     MISSING=1
fi

# Can't go on if either Postgres or Python is missing.

if [ $MISSING == 1 ]; then
     echo "$see_install"
     exit 1
fi

# Derive PostgreSQL's version number.

if [ $PGBIN != 0 ]; then
     pg_ver=$($PGBIN/pg_config --version | egrep -o "[[:digit:]].*")
     pg_ver2=$($PGBIN/pg_config --version | egrep -o "[[:digit:]]+\.[[:digit:]]+")
fi

# Check if detected versions are current.

if [ $(python -c "print int($pg_ver2 >= 7.4)") == 1 ]; then
     echo "Found PostgreSQL version $pg_ver : OK"
else
     echo "Found PostgreSQL version $pg_ver : This version is too old."
     MISSING=1
fi

if [ $(python -c "print int($py_ver2 >= 2.2)") == 1 ]; then
     echo "Found Python version $py_ver : OK"
else
     echo "Found Python version $py_ver : This version is too old."
     MISSING=1
fi

# Check for Python server-side language support in PostgreSQL.

if [ $($PGBIN/pg_config --configure | grep -o '\--with-python') ]; then
     echo "Found Python server-side language support for PostgreSQL : OK"
else
     echo "Python server-side language support for PostgreSQL was not found."
     MISSING=1
fi

# Check for Tkinter (Python interface to Tk GUI toolkit).

if $($PATHENA/build/check_Tkinter); then
     echo "Found Python's Tkinter module : OK"
else
     echo "Python's Tkinter module was not found : Missing software."
     MISSING=1
fi

# Check for PyGreSQL (Python database adapter for PostgreSQL).

if $($PATHENA/build/check_PyGreSQL); then
     echo "Found Python's pgdb module (PyGreSQL) : OK"
else
     echo "Python's pgdb module (PyGreSQL) was not found : Missing software."
     MISSING=1
fi

# ---------------- Check on directory locations ----------------

# Check that PostgreSQL directories are in standard locations for
# binary or source distribution(s).  Use alternative variable bindings
# for variant locations.

if [ $PGBIN == /usr/bin ]; then
     if [ -e /usr/share/pgsql ]; then
	echo "Found PostgreSQL directories in /usr : OK"
     elif [ -e /usr/share/postgresql ]; then
	if ! [ -e $PATHENA/config/definitions ]; then 
	   cp -p $PATHENA/build/definitions_suse $PATHENA/config/definitions
	fi
	echo "Found PostgreSQL directories in /usr : OK"
     else
	echo "PostgreSQL share directories not found in a standard location."
	MISSING = 1
     fi
elif [ $PGBIN == /usr/local/pgsql/bin ]; then
     if ! [ -e $PATHENA/config/definitions ]; then 
        cp -p $PATHENA/build/definitions_local $PATHENA/config/definitions
     fi
     echo "Found PostgreSQL directories in /usr/local : OK"
else
     echo "PostgreSQL directories not found in a standard location."
     MISSING=1
fi

# ---------------- Check on available socket ports ----------------

NEXT_PORT=$($PATHENA/build/free_port)

if [ $NEXT_PORT == 0 ]; then
    echo "Did not find a socket port : all ports in the normal range are busy."
    MISSING=1
else
    echo "Found an available socket port for PostgreSQL server : $NEXT_PORT"
    if [ $NEXT_PORT != 5439 ]; then
	if [ -e $PATHENA/config/definitions ]; then
	   cp $PATHENA/config/definitions $PATHENA/tmp/definitions
	else
	   cp $PATHENA/bin/definitions $PATHENA/tmp/definitions
	fi
	sed "s|PGPORT=5439|PGPORT=$NEXT_PORT|" $PATHENA/tmp/definitions \
            > $PATHENA/config/definitions
	rm -f $PATHENA/tmp/definitions
    fi
fi


# Abort if any of the preceding checks fails.

if [ $MISSING == 1 ]; then
     echo "$see_install"
     exit 1
fi


# ---------------- Success: create initial database ----------------

echo "
Fortunately, it appears that all of the software needed for running
Pathena is available.  In a few seconds, several initialization scripts
will be run to build a database cluster and create the Pathena database
itself.  You should expect to see several hundred lines of messages scroll
by as the scripts are processed.  When initialization is complete, you
will be left with a running PostgreSQL server.  In the final step,
Pathena's GUI client for submitting queries will be launched.
"

echo "Pausing to let you read..."
sleep 10
echo -e "...starting initialization scripts in 2 seconds.\n"
sleep 2

# Load Pathena definitions needed by following scripts.

if [ -e $PATHENA/config/definitions ];
    then DEFS=config ;
    else DEFS=bin ;
fi
source $PATHENA/$DEFS/definitions

echo "
Creating an initial PostgreSQL file cluster, then the Pathena database.
$(date)

" >> $PATHENA/log/install.log

# Build process: initialize database cluster, create Pathena database,
#                start GUI client process.

$PATHENA/build/init_pg_cluster install 2>&1 | tee -a $PATHENA/log/install.log

echo -e "Database creation begins in 2 seconds...\n"
sleep 2

$PATHENA/build/create_pathena_db new 2>&1 | tee -a $PATHENA/log/install.log



# ---------------- Prepare default environment ----------------

if [ $(python -c "print int($pg_ver2 >= 8.0)") == 1 ]; then {

sleep 2
echo -e "\nRestarting the database server to add log file options.\n"

cd $PATHENA
$PGBIN/pg_ctl -D data stop

echo "
# Following lines added by Pathena installation script
# on $(date):

redirect_stderr = true
log_directory = '$PATHENA/log'
log_filename = 'pg_stderr-%Y-%m-%d_%H%M%S.log'

log_line_prefix = '<%t> '
" >> data/postgresql.conf

#log_filename = 'pg_stderr.log'
#log_connections = true
#log_disconnections = true

# Now restart the server.

source $PATHENA/bin/pg_startup
}
fi

echo -e "\nCreating links to Pathena scripts in ~/bin (ptfind, pathena)."

if ! [ -e ~/bin ]; then
     mkdir ~/bin
fi

if [ -e ~/bin/ptfind ]; then
     echo -e "\n***** ~/bin/ptfind already exists; will not overwrite.\n"
else
     ln -s $PATHENA/bin/ptfind ~/bin/ptfind
fi

if [ -e ~/bin/pathena ]; then
     echo -e "\n***** ~/bin/pathena already exists; will not overwrite.\n"
else
     ln -s $PATHENA/bin/launch_client_pytk ~/bin/pathena
fi

if ! [ -e $PATHENA/config/preferences.conf ]; then 
     cp -p $PATHENA/config/orig_prefs.conf $PATHENA/config/preferences.conf
fi


# Index the Pathena distribution as a test, then start the client.

echo -e "\nRunning a short indexing job to test the installation..."

sleep 3   # allow for server restart time
$PATHENA/bin/index_files $PATHENA/profiles/test 0 0 0 1   # with stat update

echo -e "\nLaunching the GUI client..."

$PATHENA/bin/launch_client_pytk


echo "-----------------------------------------------

If everything went well, all items should have been installed or built
and the GUI client will be starting.  It would be a good idea to scan
the output from the preceding scripts for any error messages.  You can
also check the log files found in ~/.pathena/log.

A short indexing job using a predefined profile called 'test' should
have been run as part of this installation script.  This profile
specifies various files from the Pathena distribution for indexing.
After the GUI is up and running, you can test the installation by
submitting some practice queries against the database before trying to
index any of your own files.

Best of luck.  We hope you find Pathena useful.
"
