#!/usr/bin/env python
# vim:set sw=4 ts=4 et:
#
# ldaptool - LDAP manipulation tool
# Copyright (C) 2008  University of Bern
#
# 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 3 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, see <http://www.gnu.org/licenses/>.


import sys


def stringify_error(e):
    if isinstance(e, KeyError):
        return e.message
    return unicode(e)


if __name__ == "__main__":
    debug = '--debug' in sys.argv
    try:
        from ldaptool.commands import Main
        main = Main()
        result = main.dispatch(sys.argv[1:])
        if not result:
            sys.exit(0)
        if isinstance(result, tuple) and len(result) == 3:
            exit_code, stdout, stderr = result
            if stdout:
                print stdout
            if stderr:
                print >> sys.stderr, stderr
            sys.exit(exit_code)
        sys.exit(result)
    except Exception, e:
        if debug:
            import traceback
            traceback.print_exc(file=sys.stderr)
        else:
            print >> sys.stderr, stringify_error(e)
        if hasattr(e, 'exit_code'):
            sys.exit(e.exit_code)
        sys.exit(1)

