# HG changeset patch
# User Vincent Hatakeyama <vincent.hatakeyama@xcg-consulting.fr>
# Date 1502898140 -7200
#      Wed Aug 16 17:42:20 2017 +0200
# Node ID 3b5e05295e5eb30a5dcea2d9f7d100b9dee2e789
# Parent  929d341db31f654b4ff64e46562c7ba279160ebc
docker dev start: option to create user (also tries to detect if connection will work)

diff --git a/docker_dev_start.py b/docker_dev_start.py
--- a/docker_dev_start.py
+++ b/docker_dev_start.py
@@ -5,6 +5,7 @@
 """
 import argparse
 import logging
+import pwd
 from subprocess import call
 import sys
 import os
@@ -12,6 +13,7 @@
 import ConfigParser
 
 from netifaces import interfaces, ifaddresses, AF_INET
+from psycopg2 import connect, OperationalError
 
 # TODO auto create list of module
 
@@ -97,7 +99,13 @@
         help="Module to avoid including demo data [default: %(default)s]",
         default=None,
     )
-    # XXX add auto create user and password?
+    parser.add_argument(
+        '--create',
+        help="Create user/database (using your user)",
+        action='store_true',
+    )
+
+    # TODO detect that user is member of docker group
 
     # TODO add a way to add options to docker
     # TODO add a way to add arg to odoo
@@ -176,11 +184,40 @@
 
     # auto detect local conf
     local_conf_path = 'conf/dev/odoo.conf'
+    user = db_user 
+    password = db_password
     if os.path.isfile(local_conf_path):
         logging.info('Local configuration file found: %s' % local_conf_path)
         options.append('--volume')
         options.append('%s:/opt/odoo/etc/odoo.conf' % os.path.join(
             project_path, local_conf_path))
+        cp_local = ConfigParser.ConfigParser()
+        cp_local.read(local_conf_path)
+        if not user:
+            user = cp_local.get('options', 'db_user', 'pg')
+        if not password:
+            password = cp_local.get('options', 'db_password', 'THIS-IS-NOT-USED-DONOT-CHANGE')
+
+    # Check that connection can be done, try to create user if asked to
+    try:
+        test_connection = connect(user=user, password=password, database='postgres', host=local_ip)
+    except OperationalError as exception:
+        if nmspc.create:
+            logging.info('Cannot connect to database with user %s', user)
+            logging.info(exception)
+            logging.info('Creating user %s', user)
+            loginname = pwd.getpwuid(os.getuid())[0]
+            connection = connect(user=loginname, database='postgres')
+            with connection.cursor() as cursor:
+                # not injection safe but you are on your own machine
+                # with already full access to db
+                cursor.execute(
+                    'CREATE ROLE %s LOGIN CREATEDB PASSWORD %%s' % user, (password, ))
+            connection.commit()
+            connection.close()
+        else:
+            logging.warn('Cannot connect to database with user %s', user)
+            logging.warn(exception)
 
     # volume magic
     for addons_dir in addon_dirs: