#!/bin/bash

#you need to run this script as root eg
# sudo su postgres ./installexodus-postgresql2
#or be able to login as postgres (often disabled)
# su postgres ./installexodus-postgresql2

#should be postgres
/usr/bin/whoami

##allow local tcp/ip login (not required on debian/ubuntu and co)
#change "ident sameuser" to "md5" for all/all/127.0.0.1/32
#host    all         all         127.0.0.1/32          ident sameuser
#host    all         all         127.0.0.1/32          md5
cd $HOME
if [ -f ./data/pg_hba.conf ]; then
        test -f ./data/pg_hba.conf.preexodus || cp ./data/pg_hba.conf ./data/pg_hba.conf.preexodus
        cp ./data/pg_hba.conf ./data/pg_hba.conf.lastexodus
        egrep -v "^\w*host.*all.*127.0.0.1/.*ident" ./data/pg_hba.conf.lastexodus > ./data/pg_hba.conf
        echo host all all 127.0.0.1/32 md5 >> ./data/pg_hba.conf
fi

psql -U postgres -d template1 << EOF2
\connect template1
CREATE OR REPLACE FUNCTION exodus_call(bytea, bytea, bytea, bytea, bytea, int4, int4) RETURNS bytea AS 'pgexodus', 'exodus_call' LANGUAGE C IMMUTABLE;
CREATE OR REPLACE FUNCTION exodus_extract_bytea(bytea, int4, int4, int4) RETURNS bytea AS 'pgexodus', 'exodus_extract_bytea' LANGUAGE C IMMUTABLE;
CREATE OR REPLACE FUNCTION exodus_extract_text(bytea, int4, int4, int4) RETURNS text AS 'pgexodus', 'exodus_extract_text' LANGUAGE C IMMUTABLE;
CREATE OR REPLACE FUNCTION exodus_extract_sort(bytea, int4, int4, int4) RETURNS text AS 'pgexodus', 'exodus_extract_sort' LANGUAGE C IMMUTABLE;
-- Remaining functions are STRICT therefore never get called with NULLS -- also return NULL if passed zero length strings
CREATE OR REPLACE FUNCTION exodus_extract_text2(bytea, int4, int4, int4) RETURNS text AS 'pgexodus', 'exodus_extract_text2' LANGUAGE C IMMUTABLE STRICT;
CREATE OR REPLACE FUNCTION exodus_extract_date(bytea, int4, int4, int4) RETURNS date AS 'pgexodus', 'exodus_extract_date' LANGUAGE C IMMUTABLE STRICT;
CREATE OR REPLACE FUNCTION exodus_extract_time(bytea, int4, int4, int4) RETURNS time AS 'pgexodus', 'exodus_extract_time' LANGUAGE C IMMUTABLE STRICT;
CREATE OR REPLACE FUNCTION exodus_extract_datetime(bytea, int4, int4, int4) RETURNS timestamp AS 'pgexodus', 'exodus_extract_datetime' LANGUAGE C IMMUTABLE STRICT;
CREATE ROLE exodus LOGIN
 PASSWORD 'somesillysecret'
 CREATEDB CREATEROLE;
CREATE DATABASE exodus
 WITH ENCODING='UTF8'
   OWNER=exodus;
\df exodus*
\q
EOF2
