#!/usr/bin/env python
import sys
import os
import shutil
import encodings
import encodings.utf_8
import encodings.ascii


#############################################################

from ReleaseForge.constants import LOGGER_CONFIG_FILENAME, RELEASEFORGE_CONFIG_FILENAME, SOCKET_TIMEOUT, DEFAULT_DATA_PATH

import logging, logging.config

def check_version():
    version_tuple = sys.version_info
    version = version_tuple[0] * 100 + version_tuple[1]
    if version < 203:
        print "Python >= 2.3 required.  You are using:", sys.version
        print
        sys.exit(1)
    return version

python_version = check_version()

if python_version != 204:
    #this causes problems with python2.4 but works fine w/ 2.3
    # see:
    #  http://archives.free.net.ph/message/20050620.151244.e5390efe.en.html
    import socket
    socket.setdefaulttimeout(SOCKET_TIMEOUT)


# try to locate logger.ini
paths = ("", "/usr/share/releaseforge", "/usr/local/releaseforge")
for p in paths:
    loggerpath = os.path.join(p, LOGGER_CONFIG_FILENAME)
    if os.access(loggerpath, os.R_OK): break

try:
    logging.config.fileConfig(loggerpath)
except:
    try:
        # python 2.4
        logging.basicConfig(format="%(asctime)s - %(levelname)s - %(name)s - %(message)s")
    except:
        # python 2.3
        logging.basicConfig()


MISSING_DATA_DIR = """
Unable to determine the ReleaseForge data directory.
You must supply this path with the command line flag --data.
Alternatively, you can set the HOME enviroment variable

  eg. export $HOME=/home/somepath

For more information, please see:

  http://releaseforge.sourceforge.net/faq.html#config
"""

#############################################################

from qt import QApplication
from ReleaseForge.mainWindow import mainWindow
from ReleaseForge.settings import Settings
from optparse import OptionParser

from ReleaseForge.version import VERSION

#############################################################

def get_home():
    home = os.environ.get('HOME')
    if not home and sys.platform == 'win32':
        try:
            home = os.path.join(os.environ['HOMEDRIVE'],
                                os.environ['HOMEPATH'])
        except:
            home = None
        
    return home

def get_data_dir():
    home = get_home()

    if home: return os.path.join(home, DEFAULT_DATA_PATH)
    else:    return None


def die(msg):
    print msg
    raw_input("Press return to exit")
    sys.exit(1)
    
#############################################################

if __name__ == '__main__':
    debug = logging.getLogger("releaseforge").debug
    info = logging.getLogger("releaseforge").info    
    error = logging.getLogger("releaseforge").error
    

    default_data_dir = get_data_dir()    

    autologin = False
    parser = OptionParser()
    parser.add_option("-d", "--data",
                      dest="data_dir",
                      default=default_data_dir,
                      metavar=default_data_dir,
                      help="Specify the location of the ReleaseForge data directory")

    parser.add_option("-a", "--auto",
                      dest="autologin",
                      default=False,
                      action="store_true",
                      help="Attempt to automatically login to SourceForge and Freshmeat")

    parser.add_option("-n", "--noauto",
                      dest="noautologin",
                      default=False,
                      action="store_true",
                      help="Do not attempt to automatically login to SourceForge and Freshmeat")
    
    parser.add_option("--debug",
                      dest="debug",
                      default=False,
                      action="store_true",
                      help="Display debug information on console")

    parser.add_option("-v", "--verbose",
                      dest="verbose",
                      default=False,
                      action="store_true",
                      help="Display informational messages on console")
                      

    (options, args) = parser.parse_args()

    if options.debug:
        level = logging.DEBUG
    elif options.verbose:
        level = logging.INFO
    else:
        level = logging.WARN

    logging.getLogger().setLevel(level       )

    info("ReleaseForge v%s starting up..." % VERSION)
    
    if options.autologin: autologin = True
    
    if default_data_dir == None: die(MISSING_DATA_DIR)

    try:
        os.makedirs(options.data_dir)
        debug("created directory: %s", options.data_dir)
    except Exception, e:
        if e[0] != 17:
            die(e)

    settings_file = os.path.join(options.data_dir,
                                 RELEASEFORGE_CONFIG_FILENAME)
    debug("using settings_file: %s", settings_file)

    #### start migration -- if necessary
    
    # if a settings file already exists in the cwd (prior to 0.9.0)
    # move it to the data_dir
    if (os.access(RELEASEFORGE_CONFIG_FILENAME, os.F_OK) == True):
        try:
            shutil.move(options.settings, settings_file)
            debug("Successfully moved %s to %s",
                  RELEASEFORGE_CONFIG_FILENAME,
                  settings_file)
        except:
            error("Unable to move %s to %s",
                  RELEASEFORGE_CONFIG_FILENAME,
                  settings_file)

    #### end of migration

    settings = Settings(RELEASEFORGE_CONFIG_FILENAME,
                        options.data_dir,
                        True)

    if settings['auto_login'] == 'Enabled': autologin = True

    if options.noautologin: autologin = False

    debug("auto login: %s", autologin)

    qApp = QApplication(sys.argv)
    mw = mainWindow(settings, autologin)

    qApp.setMainWidget(mw)
    qApp.exec_loop()   


