#!/opt/opensvc/bin/python
#
# Copyright (c) 2010 Christophe Varoqui <christophe.varoqui@free.fr>'
# Copyright (c) 2010 Cyril Galibern <cyril.galibern@free.fr>'
#
# 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., 675 Mass Ave, Cambridge, MA 02139, USA.
#
import sys
import os
import optparse

#
# add project lib to path
#
pathsvc = os.path.realpath(os.path.join(os.path.dirname(__file__), '..'))
pathetc = os.path.join(pathsvc, 'etc')
sys.path.append(os.path.join(pathsvc, 'lib'))
prog = os.path.basename(__file__)

import rcExceptions as ex
import node
from rcGlobalEnv import *

try:
    from version import version
except:
    version = "dev"

n = node.Node()

__ver = prog + " version " + version
__usage = "%prog [options] command\n\n" + n.format_desc()
parser = optparse.OptionParser(version=__ver, usage=__usage)
parser.add_option("--debug", default=False,
		  action="store_true", dest="debug",
                  help="debug mode")
parser.add_option("--stats-dir", default=None,
		  action="store", dest="stats_dir",
                  help="points the directory where the metrics files are stored for pushstats")
parser.add_option("--stats-start", default=None,
		  action="store", dest="stats_start",
                  help="stats analysis start date in YYYY-MM-DD HH:MM format")
parser.add_option("--stats-end", default=None,
		  action="store", dest="stats_end",
                  help="stats analysis end date in YYYY-MM-DD HH:MM format")
parser.add_option("--module", default="",
		  action="store", dest="module",
                  help="compliance, set module list")
parser.add_option("--moduleset", default="",
		  action="store", dest="moduleset",
                  help="compliance, set moduleset list. The 'all' value can be used in conjonction with detach.")
parser.add_option("--ruleset", default="",
		  action="store", dest="ruleset",
                  help="compliance, set ruleset list. The 'all' value can be used in conjonction with detach.")
parser.add_option("--ruleset-date", default="",
		  action="store", dest="ruleset_date",
                  help="compliance, use rulesets valid on specified date")
parser.add_option("--cron", default=False,
		  action="store_true", dest="cron",
                  help="cron mode")
parser.add_option("--force", default=False,
		  action="store_true", dest="force",
                  help="force action")
parser.add_option("--symcli-db-file", default=None,
		  action="store", dest="symcli_db_file",
                  help="[pushsym option] use symcli offline mode with the specified file. aclx files are expected to be found in the same directory and named either <symid>.aclx or <same_prefix_as_bin_file>.aclx")
parser.add_option("--param", default=None,
		  action="store", dest="param",
                  help="point a node configuration parameter for the 'get' and 'set' actions")
parser.add_option("--value", default=None,
		  action="store", dest="value",
                  help="set a node configuration parameter value for the 'set --param' action")

(options, args) = parser.parse_args()

n.options = options

def do_symcli_db_file(symcli_db_file):
    if symcli_db_file is None:
        return
    if not os.path.exists(symcli_db_file):
        print "File does not exist: %s"%symcli_db_file
        return
    os.environ['SYMCLI_DB_FILE'] = symcli_db_file
    os.environ['SYMCLI_OFFLINE'] = '1'
    
do_symcli_db_file(options.symcli_db_file)

if len(args) is 0:
    parser.error("Missing action")
action = '_'.join(args)
if not action in n.action_desc:
    parser.error("unsupported action: %s"%action)

def _exit(r):
    n.close()
    sys.exit(r)

err = 0
try:
    err = n.action(action)
except ex.excError:
    import traceback
    exc_type, exc_value, exc_traceback = sys.exc_info()
    sys.stderr.write(str(exc_value)+'\n')
    _exit(1)
except KeyboardInterrupt:
    sys.stderr.write("Keybord Interrupt\n")
    _exit(1)
except:
    raise

_exit(err)
