#!/usr/bin/env python
#
# Copyright 2009 Marcelo Boveto Shima.
#
# 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.
#
# Author: marceloshima@gmail.com (Marcelo Boveto Shima)

import sys
import getopt
import traceback

import tacix.util

from tacix.freenx.FreeNXServer import FreeNXServer

prog_name="tacix-freenx-server"

logger = tacix.util.get_home_logger(prog_name)

class Usage(Exception):
    def __init__(self, msg):
        self.msg = msg

def main(argv=None):
    if argv is None:
        argv = sys.argv
    try:
        try:
            opts, args = getopt.getopt(argv[1:], ":hc:", ["help", "suspend",
                     "terminate", "startsession", "check", "resumesession", "slave", "listsessions"])

            if len(args) > 1:
                print( "More then one arguments was passed to node")
                sys.exit(1)

            if len(opts) < 1:
                freenxshell = FreeNXServer( logger=logger )
                freenxshell.run()
                sys.exit(0)

            logger.debug ("opts = %s" % opts)
            logger.debug ("args = %s" % args)

            cmd = None
            sessionid = None
            if len(args) == 1:
                sessionid = args[0]

            for opt, arg in opts:
                if opt in ("--help", "-h"):
                    print( "help" )
                    sys.exit(0)
                elif opt in ('--startsession', '--suspend', '--terminate', '--startnode',
                        '--check', '--resumesession', '--slave', '--listsessions', '-c'):
                    if cmd is not None:
                        print( "More then one command was passed to node")
                        sys.exit(1)
                    cmd = opt

            if cmd == '-c':
                freenxshell = FreeNXServer( logger=logger )
                freenxshell.run()
                sys.exit(0)
            if cmd == '--listsessions':
                freenxshell = FreeNXServer( logger=logger )
                freenxshell.list_sessions(None)
                sys.exit(0)

        except getopt.error, msg:
             raise Usage(msg)
    
    except Usage, err:
        print >>sys.stderr, err.msg
        print >>sys.stderr, "for help use --help"
        return 2

    except Exception, e:
        trace = traceback.format_exc()
        logger.error('Exiting on Exception.')

        for line in trace.split('\n'):
            logger.error('%s' % line)
        sys.exit(1)

if __name__ == "__main__":
    sys.exit(main())


