#!/usr/bin/env python
import getopt
import sys
import stat
import os
import logging
import daemon

import ajenti
import ajenti.log
from ajenti.util import PidFile

from reconfigure.configs import AjentiConfig


def usage():
    print """
Usage: %s [options]
Options:
    -c, --config <file> - Use given config file instead of default
    -v                  - Debug/verbose logging
    -d, --daemon        - Run in background (daemon mode)
    -h, --help          - This help
    --set-platform <id> - Override OS detection
    """


if __name__ == '__main__':
    log_level = logging.INFO
    config_file = ''

    try:
        opts, args = getopt.getopt(sys.argv[1:], 'hc:dv', ['help', 'config=', 'daemon', 'set-platform='])
    except getopt.GetoptError, e:
        print str(e)
        usage()
        sys.exit(2)

    is_daemon = False

    for o, a in opts:
        if o in ('-h', '--help'):
            usage()
            sys.exit(0)
        elif o in ('-v',):
            log_level = logging.DEBUG
            ajenti.debug = True
        elif o in ('-c', '--config'):
            config_file = a
        elif o in ('-d', '--start'):
            is_daemon = True
        elif o == '--set-platform':
            ajenti.platform = a

    ajenti.log.init(log_level)

    # Find default config file
    if not config_file:
        # Check for config file in /etc/ajenti/ajenti.conf
        if os.path.isfile('/etc/ajenti/config.json'):
            config_file = '/etc/ajenti/config.json'
        elif os.path.isfile(os.path.join(sys.path[0], 'config.json')):
            # Try local config file
            config_file = os.path.join(sys.path[0], 'config.json')

    if not os.path.exists(config_file):
        logging.error('Config file "%s" not found' % config_file)
        sys.exit(1)
    else:
        logging.info('Using config file %s' % config_file)

    os.chmod(config_file, stat.S_IRWXU)
    ajenti.config = AjentiConfig(path=config_file)
    ajenti.config.load()

    logging.basicConfig(level=log_level)

    if is_daemon:
        context = daemon.DaemonContext(
            pidfile=PidFile('/var/run/ajenti.pid'),
            stdout=open('/dev/null', 'w+'),
            stderr=open('/dev/null', 'w+'),
            detach_process=True
        )
        with context:
            ajenti.log.init_log_rotation()
            from ajenti import core
            core.run()
    else:
        logging.info('Ajenti starting in foreground')
        try:
            from ajenti import core
            core.run()
        except KeyboardInterrupt:
            pass
