From 00b434182e3c04976e03b94490359fa26e71ef69 Mon Sep 17 00:00:00 2001
From: Chmouel Boudjnah <chmouel@enovance.com>
Date: Thu, 2 Jan 2014 10:33:21 +0000
Subject: [PATCH] Handle more nicely when role root is already here

When using postgresql we were handling the fallback if the role root was
already here but this was still printing an error message, try to make
it a bit smarter.

Closes-Bug: #1265477
Change-Id: Ib3768dd182ab968e81038f900550f641b9a2af5c
---
 lib/databases/postgresql | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)

diff --git a/lib/databases/postgresql b/lib/databases/postgresql
index 519479ad68..60e5a33715 100644
--- a/lib/databases/postgresql
+++ b/lib/databases/postgresql
@@ -64,9 +64,13 @@ function configure_database_postgresql {
     sudo sed -i "/^host/s/all\s\+::1\/128\s\+ident/$DATABASE_USER\t::0\/0\tpassword/" $PG_HBA
     restart_service postgresql
 
-    # If creating the role fails, chances are it already existed. Try to alter it.
-    sudo -u root sudo -u postgres -i psql -c "CREATE ROLE $DATABASE_USER WITH SUPERUSER LOGIN PASSWORD '$DATABASE_PASSWORD'" || \
-    sudo -u root sudo -u postgres -i psql -c "ALTER ROLE $DATABASE_USER WITH SUPERUSER LOGIN PASSWORD '$DATABASE_PASSWORD'"
+    # Create the role if it's not here or else alter it.
+    root_roles=$(sudo -u root sudo -u postgres -i psql -t -c "SELECT 'HERE' from pg_roles where rolname='root'")
+    if [[ ${root_roles} == *HERE ]];then
+        sudo -u root sudo -u postgres -i psql -c "ALTER ROLE $DATABASE_USER WITH SUPERUSER LOGIN PASSWORD '$DATABASE_PASSWORD'"
+    else
+        sudo -u root sudo -u postgres -i psql -c "CREATE ROLE $DATABASE_USER WITH SUPERUSER LOGIN PASSWORD '$DATABASE_PASSWORD'"
+    fi
 }
 
 function install_database_postgresql {