"""
This is a script for starting postgres for development purposes
in an SMC project.
"""
import os, sys, time, util
path = os.path.split(os.path.realpath(__file__))[0]
os.chdir(path)
sys.path.insert(0, path)
PG_DATA = os.path.abspath(os.path.join(path, "../../data/postgres"))
PGHOST = os.environ.get("PGHOST", "")
if not os.path.exists(PG_DATA):
util.cmd("pg_ctl init -D '%s'" % PG_DATA)
open(os.path.join(PG_DATA, 'pg_hba.conf'), 'w').write("""
# This is safe since we only enable a socket protected by filesystem permissions:
local all all trust
# You can uncomment this and comment out the above if you want to test password auth.
#local all all md5
""")
conf = os.path.join(PG_DATA, 'postgresql.conf')
s = open(conf).read()
s += '\n'
if PGHOST:
socket_dir = PGHOST
else:
socket_dir = os.path.join(PG_DATA, 'socket')
s += "unix_socket_directories = '%s'\nlisten_addresses=''\nmax_connections=1000\n" % socket_dir
if not os.path.exists(socket_dir):
os.makedirs(socket_dir)
util.cmd("chmod og-rwx '%s'" % PG_DATA)
open(conf, 'w').write(s)
open("postgres-env", 'w').write("""#!/bin/sh
export PGUSER='smc'
export PGHOST='%s'
""" % socket_dir)
util.cmd('chmod +x postgres-env')
util.cmd("postgres -D '%s' >%s/postgres.log 2>&1 &" % (PG_DATA, PG_DATA))
time.sleep(5)
util.cmd("unset PGUSER; unset PGHOST; createuser -h '%s' -sE smc" %
socket_dir)
util.cmd("kill %s" %
(open(os.path.join(PG_DATA, 'postmaster.pid')).read().split()[0]))
time.sleep(3)
util.cmd("postgres -D '%s'" % PG_DATA)