#!/usr/bin/env python
#
# Copyright (c) 2002-2004 Juri Pakaste <juri@iki.fi>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public
# License along with this program; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.

# save the location of the script at the start before anything can modify
# sys.path
import sys
location = sys.path[0]

# wrap stdout to print unicode chars in the $TERM
import codecs
sys.stdout = codecs.lookup('utf-8')[-1](sys.stdout)

import signal
import os
import os.path
import time
import pygtk
pygtk.require("2.0")
import gtk

def find_straw_lib():
    sdir = None
    if ENV_IN_SOURCE:
        sdir = os.path.join(location, "lib")
    elif ENV_LIB_DIR:
        sdir = os.environ["STRAW_LIB"]
    else:
        for d in sys.path:
            sd = os.path.join(d, 'straw')
            if os.path.isdir(sd):
                sdir = sd

    if not sdir:
        h, t = os.path.split(os.path.split(os.path.abspath(sys.argv[0]))[0])
        if t == 'bin':
            libdir = os.path.join(h, 'lib')
            fp = os.path.join(libdir, 'straw')
            if os.path.isdir(fp):
                sdir = fp
    if not sdir:
        raise "FileNotFoundError", "couldn't find straw library dir"
    return sdir

def setup_source():
    """
    Run straw in the source tree
    """
    currentdir = os.path.dirname(os.path.abspath(sys.argv[0]))
    prefix = os.path.abspath(os.path.join(currentdir, '..'))
    print 'Generating constants.py...'
    f = open (os.path.join(sdir,'constants.py'),'w')
    f.write('APPNAME = "Straw"\n')
    f.write('VERSION = "0.26"\n')
    f.write('STRAW_URL = "http://www.nongnu.org/straw"\n')
    f.write('STRAW_REF_URL = "http://nongnu.org/straw-ref.html"\n')
    f.write('libdir = "%s"\n' % sdir)
    f.write('localedir = "%s"\n' % os.path.join(prefix, 'po'))
    f.write('datadir = "%s"\n' % os.path.join(prefix, 'data'))
    f.write('imagedir  = "%s"\n' % os.path.join(prefix, 'images'))
    f.write('gladedir  = "%s"\n' % os.path.join(prefix, 'glade'))
    f.close()
    print 'done'

def cleanup_source():
    # remove created compiled files
    import dircache
    for fn in dircache.listdir(sdir):
        filepath = os.path.join(sdir, fn)
        if filepath.endswith(".pyc"):
            os.remove(filepath)
    os.remove(os.path.join(sdir, 'constants.py'))
    print '.. exiting.'


def parse_args():
    from optparse import OptionParser
    usage = """%prog [--offline] [--enable-dbus]\nDesktop feed aggregator"""
    parser = OptionParser(usage=usage)
    parser.set_defaults(offline=False)
    parser.add_option("--offline", action="store_true", dest="offline", default=False,
                      help="run Straw in offline mode")
    (options,args) = parser.parse_args()
    return options

def run(options):
    if ENV_IN_SOURCE:
        from lib import Application, Config
    else:
        from straw import Application, Config

    # set offline to false if offline. Previous releases just rely on the
    # previous state of the 'offline' config. So if the user specifies
    # offline, the next run will still be set to offline regardless if the
    # user did not specifiy offline since it will still get the state of the
    # offline config from the previous run.
    config = Config.get_instance()
    if options.offline:
        config.offline = True
    else:
        config.offline = False
    app = Application.Application()
    # load tray if it's a standard install
    if not ENV_IN_SOURCE:
        app.load_tray()
    app.mainloop()

def main():
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    options = parse_args()
    if ENV_IN_SOURCE:
        setup_source()

    run(options)

    if ENV_IN_SOURCE:
        cleanup_source()

# setup path and environment
ENV_IN_SOURCE = os.environ.has_key("STRAW_IN_SOURCE_DIR")
ENV_LIB_DIR = os.environ.has_key("STRAW_LIB")
sdir = find_straw_lib()
if sdir not in sys.path:
    sys.path.insert(0,sdir)

if __name__ == '__main__':
    main()
