#!/usr/bin/env python
#
# Generate SQL for PostgreSQL to generate new roles in a database. We
# apply the default hashing function so that you don't have to worry
# about logging passwords when log level is set to DDL.
#
#  Examples:
#
# PGPASSWORD=choosewisely pg-create-role app_user
# pg-create-role app_01 app_02

def parse_args():
    import argparse
    def alpha_under(s):
        import re
        if not re.match(r'^[a-z_]+$', s):
            raise argparse.ArgumentTypeError('should only contain lowercase alpha and underscore')
        return s
    parser = argparse.ArgumentParser(description='Generate information we need to create postgresql roles',
                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('roles', help='Base name of the database role', type=alpha_under, metavar='role', nargs='+')
    return parser.parse_args()

def pg_hash(role, password):
    import md5
    return md5.md5('{0}{1}'.format(password, role)).hexdigest()

def main():
    import os
    args = parse_args()
    roles = {}
    for role in args.roles:
        try:
            password = os.environ['PGPASSWORD']
        except KeyError:
            password = raw_input('Password for {0}: '.format(role))
        roles[role] = pg_hash(role, password)
    print('-- Run this SQL as the postgres admin in your database')
    for role, password in roles.items():
        print("create role {0} with encrypted password 'md5{1}';".format(role, password))

if __name__ == '__main__':
    main()
