#!/usr/bin/env python
#
#  Licensed under the Apache License, Version 2.0 (the "License"); 
#  you may not use this file except in compliance with the License. 
#  You may obtain a copy of the License at 
#  
#      http://www.apache.org/licenses/LICENSE-2.0 
#     
#  Unless required by applicable law or agreed to in writing, software 
#  distributed under the License is distributed on an "AS IS" BASIS, 
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
#  See the License for the specific language governing permissions and 
#  limitations under the License. 
#
#
"""Control runtime (start/stop/status/kill) of solr instances managed by the framework"""
import os
import sys
import subprocess
from optparse import OptionParser
import logging

from solrnode.templating.env import SolrNodeEnv
from solrnode.templating.ctl import TomcatNodeCtl, SupervisordNodeCtl
    
def parse_args():
    usage = "%prog <start|stop|status|kill> <instance_name>"
    parser = OptionParser(usage=usage)
    
    parser.add_option("--instances-base-dir", dest="instances_base_dir",
                      help="Instances base dir where instances are installed.")
    
    parser.add_option("--supervisord", dest="supervisord",
                      action="store_true", default=False,
                      help="Delegate runtime control to supervisord")
    
    options, args = parser.parse_args()    
    
    if len(args) != 2:
        parser.error("Invalid number of arguments. Use -h for usage instructions.")
        
    return parser, (options, args)

def main():
    parser, (options, args) = parse_args()
    logging.basicConfig(
        level = logging.INFO,
        format = "%(levelname)s - %(message)s"
    )
    
    env = SolrNodeEnv()
    instances_base_dir = options.instances_base_dir or \
        env['fs']['instances_base_dir']

    cmd, instance_name = args

    catalina_home = env['fs']['catalina_home']
    catalina_opts = env['tomcat']['catalina_opts']
        
    ctlobj = None
    if options.supervisord:
        # Using supervisord for running service
        ctlobj = SupervisordNodeCtl(instances_base_dir=instances_base_dir,
                instance_name=instance_name, catalina_home=catalina_home,
                catalina_opts=catalina_opts)
        
    else:
        # By default, currently we fallback to tomcat runtime
        # semantics
        ctlobj = TomcatNodeCtl(instances_base_dir=instances_base_dir,
                instance_name=instance_name, catalina_home=catalina_home,
                catalina_opts=catalina_opts)
    
    ret = {
        "start": ctlobj.start,
        "stop": ctlobj.stop,
        "status": ctlobj.status,
        "kill": ctlobj.kill
    }[cmd]()
    
    return ret
    
if __name__ == "__main__":
    sys.exit(main())
    
