#!/usr/bin/python

# Copyright (C) 2013:
#    Gabes Jean, j.gabes@shinken-solutions.com
#
# This file is part of Shinken Enterprise, all rights reserved.

import sys
import optparse

from shinkensolutions.localinstall import get_local_daemons, VERSION, WARNING_COLOR, ERROR_COLOR, OK_COLOR, POSSIBLE_DAEMONS, get_local_instances_for_type, get_local_daemon_configuration_file_path, parse_ini_file, get_instance_name, \
    ADDITIONNAL_DAEMONS

if __name__ == '__main__':
    parser = optparse.OptionParser("%prog ", version="%prog: " + VERSION, description='This tool should NOT be used by users, only internal shinken tools')
    parser.add_option('--id', dest='daemon_id', help="Which daemon local id")
    parser.add_option('--type', dest='daemon_type', help="Which daemon type.")
    parser.add_option('--action', dest='action', help="what to do.")
    
    opts, args = parser.parse_args()
    
    daemon_type = opts.daemon_type
    daemon_id = opts.daemon_id
    
    if not daemon_type or not daemon_id:
        print "ERROR: missng daemon type or daemon id"
        sys.exit(2)
    
    if daemon_type not in POSSIBLE_DAEMONS and daemon_type not in ADDITIONNAL_DAEMONS:
        print "Error: no such daemon is possible"
        sys.exit(2)
    
    action = opts.action
    
    # local_instances = get_local_instances_for_type(daemon_type)
    
    if action == 'get-configuration-file':
        print get_local_daemon_configuration_file_path(daemon_type, daemon_id)
        sys.exit(0)
    
    # Get the pid file of the daemon
    if action == 'get-pid-file':
        # Grok the pid file path inside the configuration file
        cfg_p = get_local_daemon_configuration_file_path(daemon_type, daemon_id)
        
        if cfg_p.endswith('.ini'):  # look at the pidfile parameter
            r = parse_ini_file(cfg_p)
            if r is None or 'pidfile' not in r:
                print "ERROR: cannot parse ini file %s" % cfg_p
                sys.exit(2)
            print r['pidfile']
            sys.exit(0)
        if cfg_p.endswith('.cfg'):  # look at lock_file= so
            try:
                f = open(cfg_p)
                buf = f.read()
                f.close()
                for line in buf.splitlines():
                    if not line.startswith('lock_file='):
                        continue
                    # ok did find it
                    pth = line.replace('lock_file=', '').split(';', 1)[0].strip()
                    print pth
                    sys.exit(0)
            except Exception, exp:
                print "ERROR: cannot open/parse the configuration file %s: %s" % (cfg_p, exp)
                sys.exit(2)
        # still herE? no such line so
        print "ERROR: unknown configuration file %s or the pid file parameter is missing into it" % cfg_p
        sys.exit(2)
    
    # Get the pid file of the daemon
    if action == 'get-instance-name':
        print get_instance_name(daemon_type, daemon_id)
        sys.exit(0)
