#!/bin/bash

# usage : $0 [OWNER] [PGDATABASE] [import dump]
# Import dump is imported into PGDATABASE, leaving a trace log in the same directory as the import dump.

export LANG=C

export OWNER=$1
export PGDATABASE=$2
export DUMP=$3
LOG=${DUMP%/*}/${PGDATABASE}.$(date +'%Y%m%d-%H%M').log
PGUID=$(whoami)

if [ ! -f "${DUMP}" ]; then
	echo "Dump ${DUMP} doesn't exist."
	exit 1
fi

echo "Importing ${DUMP} into ${PGDATABASE}. Logging into ${LOG}"

(
set -x # L'exécution de chaque commande est affiché
# Recréation de la base initiale
dropdb ${PGDATABASE}
createdb --owner ${OWNER} --encoding UNICODE ${PGDATABASE}

# Remplissage de la base avec son contenu minimum : langage, tsearch, _int, etc.
# On prends en compte les définitions présentes dans Postgres 7.4.7, et non celles que l'on a dans la base e-dition...
createlang plpgsql ${PGDATABASE}
psql -d ${PGDATABASE} < /usr/share/postgresql/7.4/contrib/tsearch2.sql
psql -d ${PGDATABASE} < /usr/share/postgresql/7.4/contrib/_int.sql
#psql -d ${PGDATABASE} < /usr/share/postgresql/contrib/openfts.sql

zcat ${DUMP} \
	| sed \
		-e 's/LP_integration/'${OWNER}'/g' \
		-e 's/ GROUP ghs/ GROUP "www-data"/g' \
		-e 's!/home/ghs/_conf/perl/Dict/!/etc/doloforge/lib/perl/Dict/!g' \
        -e 's/ txtidx,/ text,/' \
	| psql -d ${PGDATABASE}
#		-e '/^\\connect - /s/^/-- /' \
#		-e 's/\w+@e-dition.fr/webmaster@jim.fr/g' \
#		-e 's/rkemp/'${PGUID}'/g' \
#		-e 's/Ãô/Ã´/g' \
) 2>&1 | tee ${LOG}
#	> ${LOG} 2>&1
