#!/usr/bin/env python
# -*- coding: utf-8; -*-
#
# (c) 2004-2007 Linbox / Free&ALter Soft, http://linbox.com
# (c) 2007-2011 Mandriva, http://www.mandriva.com
#
# $Id$
#
# This file is part of Mandriva Management Console (MMC).
#
# MMC 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.
#
# MMC 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 MMC.  If not, see <http://www.gnu.org/licenses/>.

import os
import os.path
import sys
from optparse import OptionParser
from mmc.site import sysconfdir
from mmc.support.config import MMCConfigParser

import mmc.agent

dft_inifile = os.path.join(sysconfdir, "mmc", "agent", "config.ini")

if __name__ == "__main__":

    # Use optparse module to parse options
    parser = OptionParser()

    # Declare options
    parser.add_option("-d", "--no-daemon", dest="daemonize", default=True, action="store_false",
                      help="Do not daemonize")
    parser.add_option("-f", "--inifile", dest="inifile", default=dft_inifile,
                      help="Path to configuration file", metavar="INIFILE")
    parser.add_option("-k", "--kill", dest="kill", default=False, action="store_true",
                      help="Kill running daemon, if any")

    # Parse arguments
    (options, args) = parser.parse_args()

    # Check config file
    if not os.path.exists(options.inifile):
        print "File '%s' does not exist." % options.inifile
	sys.exit(3)
 
    # Load configuration file
    try:
        cp = MMCConfigParser()
        cp.read(options.inifile)
    except Exception, e:
        print str(e)
        sys.exit(3)
    
    # Start the application
    app = mmc.agent.MMCApp(cp, options)
    if options.kill:
        ret = app.kill()
    else:
        ret = app.run()
    sys.exit(ret)
