#!/usr/bin/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 getpass

import tacix.util

from tacix.client.TXClient import TXClient

prog_name="tacix-client"

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:], "hs:u:p:", ["host=", "username=", "port="])

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

            host = None
            user = getpass.getuser()
            port = 22

            for opt, arg in opts:
                if opt in ("--help", "-h"):
                    print( "help" )
                    sys.exit(0)
                if opt in ("--host", "-s"):
                    host = arg
                elif opt in ("--username", '-u'):
                    user = arg
                elif opt in ("--port", "-p"):
                    port = int(arg)

            if host is None:
                print('No host to connect')
                sys.exit(1)

            txclient = TXClient(host=host, port=port)
            txclient.connect(user, getpass.getpass())
            txclient.run()
            txclient.wait_loop()

        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())


