86 lines
2.8 KiB
Python
Executable File
86 lines
2.8 KiB
Python
Executable File
#!/usr/bin/python3
|
|
import argparse
|
|
import os
|
|
import random
|
|
import string
|
|
import subprocess
|
|
import sys
|
|
|
|
|
|
publik = {
|
|
'authentic2-multitenant': {
|
|
'database': 'authentic2_multitenant',
|
|
'user': 'authentic-multitenant',
|
|
'extensions': ['unaccent', 'pg_trgm'],
|
|
},
|
|
'bijoe': {},
|
|
'chrono': {},
|
|
'combo': {'extensions': ['unaccent']},
|
|
'fargo': {},
|
|
'hobo': {},
|
|
'passerelle': {},
|
|
'wcs': {},
|
|
'welco': {},
|
|
}
|
|
|
|
|
|
def run(command, database='postgres', fake=False):
|
|
cmd = 'sudo -u postgres psql -c "%s" %s' % (command.replace('"', '\\"'), database)
|
|
if fake:
|
|
print(cmd)
|
|
else:
|
|
subprocess.run(cmd, shell=True, check=True)
|
|
|
|
|
|
def write_setting(brique, host, port, password):
|
|
if brique == 'wcs':
|
|
print('warning: setting w.c.s. connection password is not implemented')
|
|
return
|
|
settings_d = '/etc/%s/settings.d' % brique
|
|
settings = '%s/database.py' % settings_d
|
|
if not os.path.isdir(settings_d):
|
|
os.system('mkdir -p %s' % settings_d)
|
|
with open(settings, 'w') as fh:
|
|
fh.write(
|
|
"DATABASES['default']['HOST'] = '{host}'\n"
|
|
"DATABASES['default']['PORT'] = {port}\n"
|
|
"DATABASES['default']['PASSWORD'] = '{password}'".format(host=host, port=port, password=password)
|
|
)
|
|
|
|
|
|
def main(args):
|
|
for brique, data in publik.items():
|
|
database = data.get('database', brique)
|
|
user = data.get('user', brique)
|
|
extensions = data.get('extensions')
|
|
run('CREATE USER "%s";' % user, fake=args.fake)
|
|
if user == 'wcs':
|
|
run('ALTER USER wcs CREATEDB;', fake=args.fake)
|
|
if args.password:
|
|
password = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(16))
|
|
run("ALTER USER \"%s\" with password '%s';" % (user, password), fake=args.fake)
|
|
run(
|
|
"CREATE DATABASE {} WITH OWNER = \"{}\" TEMPLATE = template0 "
|
|
"LC_COLLATE = 'fr_FR.UTF-8' LC_CTYPE = 'fr_FR.UTF-8';".format(database, user),
|
|
fake=args.fake,
|
|
)
|
|
if extensions:
|
|
for e in extensions:
|
|
run('CREATE EXTENSION %s;' % e, database=database, fake=args.fake)
|
|
if not args.fake and args.password:
|
|
write_setting(brique, args.host, args.port, password)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument('--password', action='store_true', help='generate password')
|
|
parser.add_argument('--fake', action='store_true', help='dry-run')
|
|
parser.add_argument('--host', default='localhost')
|
|
parser.add_argument('--port', default='5432')
|
|
args = parser.parse_args()
|
|
|
|
if not args.fake and os.geteuid() != 0:
|
|
sys.exit('You need to have privileges to run this script, please try again with sudo.')
|
|
|
|
main(args)
|