#!/bin/sh

. /usr/share/debconf/confmodule

admin_password=$(cat /dev/urandom | tr -dc "[:print:]" | head -c 32)
admin_email="root@localhost"
dbc_name="tryton"

# get database settings from dbconfig-common
if [ -f /etc/dbconfig-common/tryton-server-postgresql.conf ]; then
    . /etc/dbconfig-common/tryton-server-postgresql.conf
fi

db_get tryton-server-postgresql/db-admin-password
if [ ! -z "$RET" ]; then
    admin_password="$RET"
fi
db_get tryton-server-postgresql/db-admin-email
if [ ! -z "$RET" ]; then
    admin_email="$RET"
fi

TRYTONPASSFILE=`mktemp`
export TRYTONPASSFILE
echo $admin_password > $TRYTONPASSFILE
unset admin_password

# The new configuration file is not yet in place, we construct the database url and use that
uri=postgresql://$dbc_dbuser:$dbc_dbpass@$dbc_dbserver
if [ ! -z $dbc_dbport ]; then
    uri="$uri":$dbc_dbport
fi
uri="$uri"/
export TRYTOND_DATABASE_URI="$uri"

#/usr/bin/trytond-admin -c /etc/tryton/trytond.conf -d "$dbc_name"  --password --email "$admin_email" --all
/usr/bin/trytond-admin -d "$dbc_name" --password --email "$admin_email" --all

# cleanup sensible data
[ "$TRYTONPASSFILE" ] && rm -f "$TRYTONPASSFILE"
#echo UNREGISTER db-admin-password | debconf-communicate tryton-server-postgresql
