#!/bin/sh

### Unit test file for the octave-database package. It can be used in both
### autopkgtest context or at build time (with option -l).

### Copyright (C) 2019 Rafael Laboissière
### Released under the terms `of the Gnu GPL, version 3 or later

### Process command line options
local=false
while getopts l opt; do
  case $opt in
      l) local=true ;;
  esac
done

### Extend PATH for the PostrgeSQL commands
PATH=$PATH:$(pg_config --bindir)

### Create temporary directory for DB data and temporary file for the
### OCtave script
DIR=$(mktemp -d)
SCRIPT=$(mktemp)

### Clean function
cleanup(){
    pg_ctl stop
    rm -rf $DIR
    rm -f $SCRIPT
}
trap "cleanup" 1 2 3 13 15

### Environment variables for PostrgeSQL client
export PGDATA=$DIR/data
export PGHOST=$DIR/socket
export PGPORT=5435
export PGUSER=test
export PGPASSFILE=$DIR/passwd

### Create the socket directory
mkdir $PGHOST

### Create a dummy password file
echo foobar > $PGPASSFILE
chmod og-r $PGPASSFILE

### Initialize the database and set the appropriate configuration variables
initdb -A trust -U $PGUSER --pwfile=$PGPASSFILE
echo "port = $PGPORT" >> $PGDATA/postgresql.conf
echo "unix_socket_directories = '$PGHOST'" >> $PGDATA/postgresql.conf

### Start the PostrgeSQL server
pg_ctl start

### Create the database needed for the unit tests
echo "create database test with owner = test;" | psql -U $PGUSER -p $PGPORT -h $PGHOST template1

### Indicate where the package is located
if [ $local = true ] ; then
    echo "addpath (genpath (sprintf ('%s/debian', pwd ())));" > $SCRIPT
else
    echo "pkg ('load', 'database');" > $SCRIPT
fi

### Lauch the tests
echo "1; function input (); endfunction; test pq_connect; demo pq_connect" >> $SCRIPT
octave-cli -q < $SCRIPT

### Final cleanup
cleanup
