import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

from django.conf import settings
import psycopg2

#psql_binary = '~/pg83/bin/'
psql_binary = 'psql'
sql_path = 'fixtures'

files = {}
EPSGDBNAME='epsg'

def find_files():
    
    import glob
    data = glob.glob('%s/EPSG_*Data_PostgreSQL.sql'%sql_path)[0]
    keys = glob.glob('%s/EPSG_*FKeys_PostgreSQL.sql'%sql_path)[0]
    tables = glob.glob('%s/EPSG_*Tables_PostgreSQL.sql'%sql_path)[0]
    
    files['data'] = data
    files['keys'] = keys
    files['tables'] = tables
    
def add_data_encoding():
    import tempfile
    import shutil
    temp_data = tempfile.mktemp()
    temp_output = tempfile.mktemp()
    f = open(files['data'])
    line = f.readline().strip()
    if line == """SET client_encoding TO 'LATIN1';""":
        f.close()
        print' not adding encoding value because it is already there'
        return
    shutil.copy(files['data'], temp_data)
    data = open(temp_data,'rb')
    
    f = open(temp_output, 'wb')
    f.write("""SET client_encoding TO 'LATIN1';\n""")
    f.write(data.read())
    f.close()
    
    shutil.copy(temp_output, files['data'])
def drop(dbname):
    con = psycopg2.connect("dbname=%s user=%s" % (dbname,settings.DATABASE_USER))
    cur = con.cursor()
    sql = "select tablename from pg_tables where tablename like 'epsg_%'"
    cur.execute(sql)
    tables = cur.fetchall()
    for i in tables:
        sql = "DROP TABLE %s CASCADE" % i[0]
        cur.execute(sql)
    con.commit()

def load(dbname):
    import os as sys
    a,b,c,d = psql_binary, sql_path, dbname, settings.DATABASE_USER
    
    sys.popen('%s -f %s -d %s -U %s' % (a,files['tables'],c,d))
     
    sys.popen('%s -f %s -d %s -U %s' % (a,files['data'],c,d))
     
    sys.popen('%s -f %s -d %s -U %s' % (a,files['keys'],c,d))

if __name__ == '__main__':
  print 'Dropping epsg tables if they exist...'
  drop(EPSGDBNAME)
  drop(settings.DATABASE_NAME)
  print 'Loading epsg tables...'
  find_files()
  add_data_encoding()

  load(EPSGDBNAME)
  load(settings.DATABASE_NAME)

