#!/bin/sh
# database creation script for gnuhealth-server

set -e

# Source the config file from dbconfig-common
. /etc/dbconfig-common/gnuhealth-server.conf

GNUHEALTH_USER="gnuhealth"
GNUHEALTH_HOMEDIR="/var/lib/gnuhealth"
GNUHEALTH_NODBUPDATEFILE="${GNUHEALTH_HOMEDIR}/no-db-update"
GNUHEALTH_CONFFILE="/etc/gnuhealth/gnuhealth-server.conf"

# Create system user
adduser --home ${GNUHEALTH_HOMEDIR} --quiet --system --group ${GNUHEALTH_USER}

tf=`su --shell /bin/sh -c "tempfile 2>/dev/null" ${GNUHEALTH_USER}`
# Use the same password for the Tryton admin as for the database
echo $dbc_dbpass > $tf
# Initialize the gnuhealth database
su --shell /bin/sh -c "TRYTONPASSFILE=$tf trytond --database=gnuhealth --init=all --config=${GNUHEALTH_CONFFILE}" ${GNUHEALTH_USER}
rm -f $tf

# Change database owner (needs to be run as postgres user, as PostgreSQL's
# default authentication is set to peer method)
su --shell /bin/sh -c "psql -U postgres -c 'ALTER DATABASE gnuhealth OWNER TO gnuhealth'" postgres

# Create a temporary file that indicates we've just created the database.
# Will be used in postinst to know not to update the database.
touch ${GNUHEALTH_NODBUPDATEFILE}

exit 0
