# startup script for production server hosted via cherrypy

import os
import cherrypy
import socket
import wnsq.settings_prod as settings
from django.core.wsgi import get_wsgi_application
from django.core.management import call_command
import subprocess

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "wnsq.settings_prod")
pg_path = os.environ.get("PGSQL") # grab pg path from environment var, .bat sets this
pg_ctl_binary = pg_path + "\\pg_ctl.exe"

# -c timezone=\'America/New_York\'
# launch db server
try:
    print("(re)starting database system...")
    with open("timezone.cfg") as tzFile:
        tzString = tzFile.readline()
        subprocess.call([pg_ctl_binary, '-D', 'database', 'restart', '-o', '-p 5987 -ctimezone={0}'.format(tzString)], stderr=subprocess.STDOUT)
except Exception as cpErr:
    print("failed to start db system.")
    print(cpErr)

application = get_wsgi_application()

cherrypy.tree.graft(application, '')

static_config = {
    'tools.staticdir.on': True,
    'tools.staticdir.dir': os.path.join(settings.BASE_DIR, 'core/static/'),
    'tools.expires.on': False
}

media_config = {
    'tools.staticdir.on': True,
    'tools.staticdir.dir': os.path.join(settings.BASE_DIR, '../docs/'),
    'tools.expires.on': False
}

print('current machine ips')
print([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1])

cherrypy.tree.mount(None, settings.STATIC_URL, {'/': static_config})
cherrypy.tree.mount(None, settings.MEDIA_URL, {'/': media_config})

cherrypy.config.update({'server.socket_host': '0.0.0.0',
                        'server.socket_port': 8080})

# subscribe to ctrl+c
if hasattr(cherrypy.engine, 'console_control_handler'):
    cherrypy.engine.console_control.handler.subscribe()

if hasattr(cherrypy.engine, "signal_handler"):
    cherrypy.engine.signal_handler.subscribe()

cherrypy.engine.start()
cherrypy.engine.block()

try:
    print("shutting down database system.")
    subprocess.call([pg_ctl_binary, '-D', 'database', 'stop'])
except Exception as cpErr:
    print("failed to shutdown the database server.")
    print(cpErr)