#!/bin/sh

user=diaspora
dbname=diaspora_production

. /etc/diaspora/diaspora-common.conf

# Find out dbtype and run only for pgsql
test -f /etc/dbconfig-common/diaspora-common.conf && . /etc/dbconfig-common/diaspora-common.conf

test -f ${diaspora_database_yml_private} ||\
cp ${diaspora_database_yml_example} ${diaspora_database_yml_private}
chmod go-r ${diaspora_database_yml_private}

if [ "$dbc_dbtype" = "mysql" ]; then
  # Switch to mysql adapter, ugly hack, see #818863
  sed -i 's/DB=postgres/DB=mysql/' ${diaspora_conf_private}
  sed -i 's/BUNDLE_WITH=postgresql/BUNDLE_WITH=mysql/' ${diaspora_conf_private}
  sed -i 's/\# <<: \*mysql/<<: \*mysql/' ${diaspora_database_yml_private}
  sed -i 's/<<: \*postgres/\# <<: \*postgres/' ${diaspora_database_yml_private}
  sed -i "1,10s/password: \"\"/password: \"$dbc_dbpass\"/" ${diaspora_database_yml_private}
  exit 0
fi

# Switch to postgres adapter, ugly hack, see #818863
sed -i 's/<<: \*mysql/\# <<: \*mysql/' ${diaspora_database_yml_private}
sed -i 's/\# <<: \*postgres/<<: \*postgres/' ${diaspora_database_yml_private}

echo "Make $user user owner of $dbname database..."
sudo -u postgres psql -c "ALTER DATABASE $dbname OWNER to $user;" || {
  exit 1 
  }

echo "Allow $user user to create databases..."
sudo -u postgres psql -c "ALTER USER $user CREATEDB;" || {
  exit 1 
  }
echo "Grant all privileges to $user user..."
sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE template1 to $user;" || {
  exit 1
  }
