#!/usr/bin/python
# -*- coding: utf-8 -*-

"""holds the central program for running the murrayb daemon"""

import sys, os, time, traceback

# set the paths...
sys.path.extend(['core','jabberserver', 'murray-crypto', 'server', 'xml'])
# and import our own modules

import globalv

#Flag for all Threads to exit if set
globalv.RUNNING = True

#setting global variables and settings
#meet MURRAY_HOME - the place to be for config files
if os.name == 'nt':
    globalv.MURRAY_HOME = os.path.join(os.getenv('APPDATA'), 'murray')
elif os.name == 'posix':
    globalv.MURRAY_HOME = os.path.expanduser('~/.config/murray')
else:
    globalv.MURRAY_HOME = os.path.expanduser('~/.config/murray')

if '--home' in sys.argv:
    globalv.MURRAY_HOME = os.path.expanduser(sys.argv[sys.argv.index('--home' + 1)])

if not os.path.exists(globalv.MURRAY_HOME) or not os.path.isdir(globalv.MURRAY_HOME):
    os.mkdir(globalv.MURRAY_HOME)

import murray_crypto as crypto

#Our global configuration file    
globalv.GLOBAL_CONFIG = os.path.join(globalv.MURRAY_HOME, 'murrayd.conf')
#global log file
globalv.GLOBAL_LOG = os.path.join(globalv.MURRAY_HOME, 'murrayd.log')
#port for our server
globalv.PORT = 4711
#Port for the local XMPP-Server
globalv.XMPPPORT = 5222
#ip version (currently only ipv4 supported)
globalv.IP_VERSION = 4
#our own ip - ###TODO: Autmatic setting
globalv.IP = ''
globalv.MURRAY_ID = crypto.murrayid()
#Our Nickname
globalv.ALIAS = 'Change-Me!'
#Known Peers defined in config file
globalv.KNOWN_PEERS = []
#Known Peers Storage
globalv.KNOWN_PEERS_FILE = os.path.join(globalv.MURRAY_HOME, 'known_peers.dict')
#Buddilist Storage
globalv.CLIST_FILE = os.path.join(globalv.MURRAY_HOME, 'clist.dict')
#protocol to be used - TCP or UDP
globalv.PROTO = 'tcp'
#status as displayed
globalv.SHOW = None
#statusmessage
globalv.STATUS = None

#read config file
globalv.readConffile()
    
###Startup
from running import *
import logger
print 'Starting MurrayB-Daemon...'

globalv.RUNNING = True

#supernode?
if ('-s' in sys.argv) or ('--supernode' in sys.argv):
    globalv.SUPERNODE = True
else:
    globalv.SUPERNODE = False


try:
        Running()
except:
        logger.write(str(sys.exc_type) + str(sys.exc_value) + \
        str(traceback.extract_tb(sys.exc_traceback)) + '\n')
        print '''Ooops... this error could not be handled... consult ''', globalv.GLOBAL_LOG, ''' for further information \n
        \n stopping cowardly'''
        logger.close()
        sys.exit(1)

