Simplify database selection

Do not require every script that sources stackrc to also
source lib/databases.

* Move use_databases() to functions
* Set DATABASE_TYPE in stackrc
* Allow setting DATABASE_TYPE in localrc to work
  (use_database() essentially just sets DATABASE_TYPE at this stage
  so continuing to use it is equivalent)
* Validate DATABASE_TYPE in stack.sh.
* Change sudo to postgresql user to go through root to eliminate
  password prompt
* fix use_database error condition

Change-Id: Ibb080c76e6cd7c6eebbb641a894d54b1dde78ca6
diff --git a/stack.sh b/stack.sh
index f250c6b..ec10b11 100755
--- a/stack.sh
+++ b/stack.sh
@@ -29,8 +29,6 @@
 # and ``DISTRO``
 GetDistro
 
-# Import database library (must be loaded before stackrc which sources localrc)
-source $TOP_DIR/lib/database
 
 
 # Settings
@@ -92,6 +90,14 @@
 # Sanity Check
 # ============
 
+# Import database configuration
+source $TOP_DIR/lib/database
+
+# Validate database selection
+# Since DATABASE_BACKENDS is now set, this also gets ENABLED_SERVICES
+# properly configured for the database selection.
+use_database $DATABASE_TYPE || echo "Invalid database '$DATABASE_TYPE'"
+
 # Remove services which were negated in ENABLED_SERVICES
 # using the "-" prefix (e.g., "-rabbit") instead of
 # calling disable_service().