#!/usr/bin/env python

import os, inspect, optparse, sys, psycopg

def main(inp=sys.argv[1:]):
    """
    creates a new user and schema in your database, 
    prefixed with your username
    
    i.e. 
        %prog foo
    creates user $USER_foo and schema $USER_foo in database named $USER
    the schema will be owned by $USER_foo
    """
    parser = optparse.OptionParser(usage=("%prog newuser password" + "\n\n" +
                                            inspect.getdoc(main)))
    options, args = parser.parse_args(inp)
    try:
        new_schema_name, password = args
    except ValueError:
        parser.error("incorrect args")
    
    user = os.environ['USER']
    new_schema = new_schema_name
    new_user = new_schema
    
    print "going to create user %s with password '%s'" % (new_user, password)
    print "going to create schema %s in database %s" % (new_user, user)
    print "OK? [y/n] ",
    if sys.stdin.readline().strip().lower() != 'y':
        print "aborted"
        sys.exit(1)
    else:
        conn = psycopg.connect("user=postgres password=tymeOUT dbname=%s" % user)
        c = conn.cursor()
        # create a limited user ...
        c.execute(  "create role %s nosuperuser inherit login password '%s'" %
                    (new_user, password))
        c.execute("create schema %s" % new_schema)
        c.execute(  "grant all on schema %s to %s" % 
                    (new_schema, new_user))
        c.execute(  "alter user %s set search_path = %s, pg_catalog" % 
                    (new_user, new_schema))
        conn.commit()
        print "done!"

if __name__ == '__main__':
    main()