#!/bin/sh

# this script will change encoding in your database. It's somewhat
# Debian specific (pathnames) and users Latin 2 as encoding.

# check if you have locale vars

if [ -z "`set | grep LC_`" ]; then
	echo "no LC_ variables in enviroment!"
	exit 1
fi

# default setup (seems resonable)

new=~postgres/data.new
old=~postgres/data
bak=~postgres/data.bak

# init new db

mkdir $new
initdb --encoding latin2 -d $new

/usr/lib/postgresql/bin/postmaster -D $new -p 6666 &
new_pid=$!

# stop original postgresql
pg_ctl stop

sleep 5

/usr/lib/postgresql/bin/postmaster -D $old -p 6665 &
old_pid=$!

# wait for new postmaster(s) on 666[56] to start

while ! psql -q -p 6666 template1 -c ""
do
	sleep 5
done

while ! psql -q -p 6665 template1 -c ""
do
	sleep 5
done

# dump from old db to new

/usr/lib/postgresql/bin/pg_dumpall -p 6665 | psql -q -p 6666 template1

# stop my postmasters

sleep 5

kill -SIGTERM $old_pid $new_pid

sleep 5

# wait for them to stop

while psql -q -p 6666 template1 -c ""
do
	sleep 5
done

while psql -q -p 6665 template1 -c ""
do
	sleep 5
done

sleep 5

# move data dirs around

mv $old $bak
mv $new $old

# start original postmaster

pg_ctl start

