#!/usr/bin/python

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

import os
import sys
import optparse

try:
    import shinken
except ImportError:
    print 'Cannot import shinken lib, please install it before launching this tool'
    sys.exit(2)

from shinkensolutions.localinstall import VERSION, ERROR_COLOR, ERROR_SHELL_TAG, RESET_SHELL_TAG, OK_COLOR, check_root, POSSIBLE_DAEMONS, get_local_daemon_configuration_file_path, remove_local_daemon_instance, is_local_daemon_instance_exists, \
    stop_daemon

# This command is not allowed for specific types
_UN_ALLOWED_DAEMONS = set(['arbiter', 'synchronizer'])
ALLOWED_DAEMONS = list(set(POSSIBLE_DAEMONS) - _UN_ALLOWED_DAEMONS)
ALLOWED_DAEMONS.sort()

# After the help, we want to give some examples
_MAGENTA = '\033[95m'
EXAMPLE_STRING = '''
Examples:
# %sStep1 [on the scheduler server]%s: first list all daemons on the server:
  shinken-daemons-list
# %sStep2 [on the scheduler server]%s: then remove the scheduler with the id 2:
  shinken-daemons-remove --ini --type=scheduler --id=2
''' % (_MAGENTA, RESET_SHELL_TAG, _MAGENTA, RESET_SHELL_TAG)

# WARNING/HERESY: By default the formatter strip new lines, do not allow this
formatter = optparse.TitledHelpFormatter(width=200)
formatter._format_text = lambda txt: txt


# If there is a critical error: print it in RED and exit in bad state
def exit_error(txt):
    print "%sERROR: %s%s" % (ERROR_SHELL_TAG, txt, RESET_SHELL_TAG)
    parser.print_help()
    sys.exit(2)


if __name__ == '__main__':
    parser = optparse.OptionParser("%prog", version="%prog: " + VERSION, formatter=formatter, description='This tool is used to remove daemons on the local server', epilog=EXAMPLE_STRING)
    parser.add_option('--ini', dest='is_ini', action='store_true', help="[Mandatory] Remove daemon locally on the server.")
    parser.add_option('-t', '--type', type='choice', dest='daemon_type', choices=ALLOWED_DAEMONS, help="Daemon type to remove. Must be in: %s" % ', '.join(ALLOWED_DAEMONS))
    parser.add_option('--id', dest='daemon_id', help="ID of the daemon to remove. They can be listed with the command: shinken-daemons-list.")
    
    opts, args = parser.parse_args()
    
    # If not root, exit
    check_root()
    
    if not opts.is_ini:
        exit_error('Please use the --ini parameter.')
    
    daemon_type = opts.daemon_type
    if not daemon_type:
        exit_error('Please select a valid daemon type option with the --type parameter.')
    
    daemon_id = opts.daemon_id
    if daemon_id is None:
        exit_error('Please add the ID of the daemon to delete with the --id parameter. You can have the daemon ids with the shinken-daemons-list command')
        sys.exit(2)
    
    # We need to delete a daemon. Currently, ids=0 daemons are protected (they are the default ones)
    if daemon_id == '0':
        exit_error('ERROR: you cannot remove default daemons (with id=0)')
        sys.exit(2)
    
    if not is_local_daemon_instance_exists(daemon_type, daemon_id):
        print '\033[%dm ERROR\033[0m there is no such daemon %s defined on the local server' % (ERROR_COLOR, ('%s [id:%s]' % (daemon_type, daemon_id)))
        sys.exit(2)
    
    # If remove, try to stop the daemon
    stop_daemon(daemon_type, daemon_id)
    
    ini_path = get_local_daemon_configuration_file_path(daemon_type, daemon_id)
    
    if os.path.exists(ini_path):
        os.unlink(ini_path)
    
    remove_local_daemon_instance(daemon_type, daemon_id)
    
    print ' %s is \033[%dm REMOVED\033[0m from local server' % (('%s [id:%s]' % (daemon_type, daemon_id)), OK_COLOR)
