#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
#
#       upload-picture
#       
#       Copyright 2011 Voldemar Khramtsov <harestomper@gmail.com>
#       
#       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., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.

import os
import sys
import getopt
import signal

from itmagesd.daemonclass import Daemon
from itmagesd.engine import Engine
from itmagesd.common import stat
from itmagesd.common import USERCONFIGDIR
from itmagesd.tools import conf_get
from itmagesd.tools import tempclear
from itmagesd.tools import message_dump
from itmagesd.tools import find_alive_socket

samename = os.path.basename(sys.argv[0])
splname = os.path.splitext(samename)[0]
pidfile = os.path.join(USERCONFIGDIR, '%s.pid' % splname)
usage = '''Usage:
%s [options] [list_of_files]
 -d | --daemon           Start this script as daemon.
 -v | --verbose          Enable a verbose mode.
 -h | --help             Show this message, and exit.
 --stop                  If it's already the daemon, stop running it.
 --restart               If it's already the daemon, restart running it.
 --status                Get status for the daemon.
 --stdout=FILENAME       Set filename to standart output for daemon.
                         [Default /tmp/itdaemon.out]
 --stderr=FILENAME       Set filename to standart output errors for daemon.
                         [Default /tmp/itdaemon.err]
 --pidfile=FILENAME      Set specified filename for .pid file.
                         [Default %s]
''' % (samename, pidfile)

def main(filelist=[]):

    try:
        argv = os.environ['NAUTILUS_ITMAGES_SESLECTED_FILES']
    except KeyError:
        argv = filelist
    else:
        argv = eval(argv)
        os.environ.pop('NAUTILUS_ITMAGES_SESLECTED_FILES')

    sock = find_alive_socket()

    if sock:
        for fname in argv:
            dump = message_dump("add_new_item", filename=fname)
            sock.send(dump)

        sock.close()
    else:
        eng = Engine()

        def handler(code, page):
            signal.signal(signal.SIGALRM, signal.SIG_DFL)
            signal.alarm(2)
            eng.quiting(None)
            sys.stdout.write('\r\rInterrupted\n')
            
        signal.signal(signal.SIGINT, handler)
        try:
            eng.main()
        except KeyboardInterrupt:
            handler(0, 0)
    return 0


if __name__ == "__main__":

    class IT_Daemon(Daemon):
        filelist = []

        def run(self):
            main(self.filelist)

    stat.isdaemon = False
    stat.verbose = False
    action = None
    fstdout = '/tmp/itdaemon.out'
    fstderr = '/tmp/itdaemon.err'
    pid_file = pidfile
    filelist = []

    try:
        opts, args = getopt.getopt(sys.argv[1:], 'hdv', ['help', 'stop',
                                        'daemon', 'restart', 'status', 'stdout=',
                                        'stderr=', 'pidfile=', 'verbose'])
    except getopt.GetoptError:
        sys.stdout.write(usage)
        sys.exit(1)

    def get_availabled():
        from itmages.indicators import modules
        return modules.keys()

    for o, a, in opts:
        if   o == '--stop':
            action = 'stop'

        elif o == '--status':
            action = 'status'

        elif o == '--restart':
            action = 'restart'

        elif o == '--stdout':
            fstdout = a

        elif o == '--stderr':
            fstderr = a

        elif o == '--pifile':
            pid_file = a

        elif o in ('-h', '--help'):
            action = 'help'

        elif o in ('-v', '--verbose'):
            stat.verbose = True

        elif o in ('-d', '--daemon'):
            stat.isdaemon = True
            action = 'start'

    daemon = IT_Daemon(pidfile=pid_file, stdout=fstdout, stderr=fstderr)
    daemon.filelist = args

    if action == 'start':

        if daemon.status():
            daemon.run()
        else:
            daemon.start()

    elif action == 'stop':
        daemon.stop()

    elif action == 'restart':
        daemon.stop()
        daemon.start()

    elif action == 'status':
        daemon.status()

    elif action == 'help':
        sys.stdout.write(usage)
        sys.exit(0)

    else:
        daemon.run()


###
