"""
This is a script for starting postgres for development purposes on a laptop.
"""
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.join(path, "postgres_data")
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'
socket_dir = os.path.join(PG_DATA, 'socket')
s += "unix_socket_directories = '%s'\nlisten_addresses=''\n"%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)