from fabric.api import hide, put, run, settings, task
from StringIO import StringIO

from . import apt

@task
def ensure():
    with settings(user='root'):
        run('wget --quiet https://www.postgresql.org/media/keys/ACCC4CF8.asc')
        run('apt-key add ACCC4CF8.asc')
        run('rm ACCC4CF8.asc')
        with hide('commands'):
            codename = run('lsb_release --codename --short')
        sources = StringIO()
        sources.name = 'pgdg.list'
        sources.write('deb http://apt.postgresql.org/pub/repos/apt/ {}-pgdg main\n'.format(codename))
        put(sources, '/etc/apt/sources.list.d/pgdg.list')
        apt.update()
        apt.ensure('postgresql')

@task
def create_user(user):
    with settings(user='root'):
        run('su --login --command "dropuser --if-exists {}" postgres'.format(user))
        run('su --login --command "createuser {}" postgres'.format(user))

@task
def create_db(db, user):
    with settings(user='root'):
        run('su --login --command "dropdb --if-exists {}" postgres'.format(db))
        run('su --login --command "createdb --owner={} {}" postgres'.format(user, db))

@@ -680,20 +680,20 @@
 ask%0Adef 
-crea
+dele
 te_user(
@@ -814,16 +814,100 @@
 t(user))
+%0A%0A@task%0Adef create_user(user):%0A    delete_user(user)%0A    with settings(user='root'):
 %0A       
@@ -988,20 +988,20 @@
 def 
-crea
+dele
 te_db(db
 , us
@@ -1000,14 +1000,8 @@
 b(db
-, user
 ):%0A 
@@ -1111,16 +1111,97 @@
 at(db))%0A
+@task%0Adef create_db(db, user):%0A    delete_db(db)%0A    with settings(user='root'):%0A
         

add delete_db and delete_user