#! /bin/sh


# Function to get and set sequence
seq() {
   seq_name="$1_$2_seq"
   seq_value=`psql -d ce_pub -c "SELECT last_value FROM $seq_name;" | awk "NR==3 {print}"`
   echo "SELECT setval ('$1_$2_seq', $seq_value);" >> ce_pub-dump.sql
}

if [ ! -f ce_pub-dump.sql ]; then
   pg_dump -a ce_pub > ce_pub-dump.sql || exit 1

   seq shop_types type_id
   seq raw_maillog mail_id
   seq motd msg_id

   vim ce_pub-dump.sql
fi

exec >log 2>err
destroydb ce_pub

createdb ce_pub || exit 1
psql ce_pub < create-main-tables.sql || exit 1

if [ "$1" = -c ]; then
   sed 's/-- # //' create-codif.sql | psql ce_pub || exit 1
   psql -d ce_pub -c "DELETE FROM param_str WHERE param_id = 6;" || exit 1
else
   psql ce_pub < create-codif.sql || exit 1
fi

psql ce_pub < create-other-tables.sql || exit 1

psql ce_pub < ce_pub-dump.sql || exit 1

psql ce_pub < grant-to-www.sql || exit 1
psql ce_pub < grant-to-media.sql || exit 1

exit 0
