#!/usr/bin/env python

"""
Run the NSDB jump-start administration tool
"""

__copyright__ = """
Copyright 2013 Oracle.  All rights reserved.

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2.0
as published by the Free Software Foundation.

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 version 2.0 for more details.

A copy of the GNU General Public License version 2.0 is
available here:

    http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt
"""

import sys
import os
import argparse
import logging as log

sys.path.insert(1, '${prefix}/lib/python2.7/site-packages')

try:
    from PyFedfs.run import EXIT_FAILURE

    from PyFedfs.jumpstart.install import subcmd_install
    from PyFedfs.jumpstart.backup import subcmd_backup, subcmd_restore
    from PyFedfs.jumpstart.status import subcmd_status
except ImportError:
    print >> sys.stderr, \
        'Could not import a required Python module:', sys.exc_value
    sys.exit(1)


def main():
    """
    Domainroot helper main program

    Returns a shell exit status value
    """
    if os.getegid() != 0:
        print >> sys.stderr, 'You must be root to run nsdb-jumpstart.'
        return EXIT_FAILURE

    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter,
        description='Jump-start a simple NSDB service',
        epilog='''\
Copyright 2013 Oracle.  All rights reserved.

License GPLv2: <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt>
This is free software.  You are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.''')
    parser.add_argument('--version',
                        help='Display the version of this command',
                        action='version',
                        version='fedfs-utils 0.10.5')
    parser.add_argument('--statedir',
                        help='FedFS state dir (default /var/lib/fedfs)',
                        default='/var/lib/fedfs')
    subparsers = parser.add_subparsers(title='Sub-commands')

    install_parser = subparsers.add_parser('install',
                                           help='Install an NSDB')
    install_parser.add_argument('--security',
                                choices=['none', 'tls'],
                                help='security strength')
    install_parser.set_defaults(func=subcmd_install)

    backup_parser = subparsers.add_parser('backup',
                                          help='Backup the local NSDB')
    backup_parser.add_argument('--nocompress',
                               help='Do not compress the backup file',
                               action='store_true')
    backup_parser.set_defaults(func=subcmd_backup)

    restore_parser = subparsers.add_parser('restore',
                                           help='Restore NSDB from backup')
    restore_parser.add_argument('backup',
                                nargs='?', default='',
                                help='Which backup to restore')
    restore_parser.set_defaults(func=subcmd_restore)

    status_parser = subparsers.add_parser('status',
                                          help='Display status of NSDB '
                                               'service')
    status_parser.set_defaults(func=subcmd_status)

    args = parser.parse_args()

    if not os.path.isdir(args.statedir):
        try:
            os.mkdir(args.statedir)
        except OSError:
            print >> sys.stderr, \
                'Failed to create ', args.statedir
            return EXIT_FAILURE

    logfile = os.path.join(args.statedir, 'nsdb-jumpstart.log')
    log.basicConfig(level=log.DEBUG,
                    format='%(asctime)s %(name)-12s '
                           '%(levelname)-8s %(message)s',
                    datefmt='%m-%d %H:%M',
                    filename=logfile,
                    filemode='a')
    console = log.StreamHandler()
    console.setLevel(log.INFO)
    formatter = log.Formatter('%(levelname)-8s: %(message)s')
    console.setFormatter(formatter)
    log.getLogger('').addHandler(console)

    return args.func(args)


try:
    if __name__ == '__main__':
        sys.exit(main())
except (SystemExit, KeyboardInterrupt, RuntimeError):
    sys.exit(1)
