#! /usr/bin/python

# Copyright (c) 2001-2009 Twisted Matrix Laboratories.
# See LICENSE for details.

import logging
import sys
import os

LOGGER_NAME = "twistd"
base_location = "/var/log/opscenter/" if "OPSC_IS_PACKAGE" in os.environ else "log/"
file_name = '%sstartup.log' % base_location
log_format = "%(asctime)s [opscenterd] %(levelname)s: %(message)s"

if not os.path.exists(base_location):
    os.makedirs(base_location)

logging.basicConfig(
     filename=file_name,
     level=logging.INFO,
     format= log_format,
     datefmt='%H:%M:%S',
     filemode = 'w'
 )

log_formatter = logging.Formatter(log_format)
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
console.setFormatter(log_formatter)
log = logging.getLogger(LOGGER_NAME)
log.addHandler(console)

log.info("Loading OpsCenter...")

# give preference to anything with "opscenter" in the path, but give
# higher preference to anything under the tarball/install directory
log.info("Updating system path")
exe_path = os.path.abspath(sys.argv[0])
tarball_path = os.path.normpath(os.path.join(exe_path, os.pardir, os.pardir))

to_shift = filter(lambda d: "opscenter" in d, sys.path)
to_shift += filter(lambda d: tarball_path in d, sys.path)

for directory in to_shift:
    sys.path.remove(directory)
    if "lib-fallback" not in directory:
        sys.path.insert(0, directory)
    else:
        sys.path.append(directory)

if hasattr(os, "getuid") and os.getuid() != 0:
    sys.path.insert(0, os.path.abspath(os.getcwd()))

log.info("Importing twisted logging")
from twisted.python.log import PythonLoggingObserver
log.info("Finished importing twisted logging")

# Enable logging at the python logger level and log twisted messages
observer = PythonLoggingObserver(loggerName=LOGGER_NAME)
observer.start()
log.info("Opscenterd starting up...")

from twisted.scripts.twistd import run
run()