#!/bin/bash

if [ -f /var/lib/nethserver/webtop/backup/webtop.sql ]; then
    drop_sql=`mktemp`
    chown postgres:postgres $drop_sql
    # drop all existing connections to the db and block new ones
    echo "UPDATE pg_database SET datallowconn = 'false' WHERE datname = 'webtop5';" >> $drop_sql
    echo "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'webtop5';" >> $drop_sql
    # drop the db, then recreate it
    echo "DROP DATABASE webtop5;" >> $drop_sql
    password=`perl -e "use NethServer::Password; print NethServer::Password::store('webtop5');"`
    echo "CREATE database webtop5; CREATE USER sonicle WITH PASSWORD '$password'; GRANT ALL PRIVILEGES ON DATABASE webtop5 to sonicle;" >> $drop_sql 
    # allow new connections to db
    echo "UPDATE pg_database SET datallowconn = 'true' WHERE datname = 'webtop5';" >> $drop_sql
    su - postgres -c "psql < $drop_sql" >/dev/null
    su - postgres -c "psql webtop5 < /var/lib/nethserver/webtop/backup/webtop.sql" >/dev/null
    rm -f $drop_sql
fi
