#!/bin/bash

# data available here:
# curl -sL http://dl.free.fr/ovxwiBwDD -o textes.dump

shopt -s -o errexit nounset

PRE=/tmp/icu
PGDATA=/tmp/icu/pgdata
PGPORT=5432

export PGDATA PGPORT

# build/install current banch
make -j4 install >/dev/null
pushd contrib/pg_prewarm >/dev/null
make -j4 install >/dev/null
popd >/dev/null

# cleanup previous run
$PRE/bin/pg_ctl -s -m immediate stop 2>/dev/null|| true
rm -fr "${PGDATA:?}"

# create & start new instance
$PRE/bin/initdb -U postgres -N -k "$PGDATA" >/dev/null 2>&1
$PRE/bin/pg_ctl -s -w -l "$PRE/postgresql.log" start

# create utf8 and latin1 database for tests
$PRE/bin/createdb -E unicode uni
$PRE/bin/createdb -E latin1 -l fr_FR -T template0 latin

for db in uni latin; do

    $PRE/bin/pg_restore -d "$db" textes.dump

    $PRE/bin/vacuumdb -qz "$db"

    $PRE/bin/psql -d "$db" -XAto /dev/null <<-EOF
    CREATE EXTENSION IF NOT EXISTS pg_prewarm;
    SELECT * FROM pg_prewarm('textes'::regclass);
    ALTER DATABASE $db SET work_mem TO '256MB';
    ALTER DATABASE $db SET max_parallel_workers_per_gather TO 0;
    ALTER TABLE textes ALTER COLUMN contenu TYPE text COLLATE digitslast
	EOF
    \time -f %e $PRE/bin/psql -d "$db" -XAto /dev/null <<-EOF
    SELECT * FROM textes ORDER BY contenu;
	EOF

done

#$PRE/bin/pg_ctl -s -m immediate stop
#rm -fr "${PGDATA:?}"

