#! /usr/bin/ensim-python
######################################################################
#
# Copyright (c) Ensim Corporation 2000, 2001   All Rights Reserved.
#
# This software is furnished under a license and may be used and copied
# only  in  accordance  with  the  terms  of such  license and with the
# inclusion of the above copyright notice. This software or any other
# copies thereof may not be provided or otherwise made available to any
# other person. No title to and ownership of the software is hereby
# transferred.
#
# The information in this software is subject to change without notice
# and  should  not be  construed  as  a commitment by Ensim Corporation.
# Ensim assumes no responsibility for the use or  reliability  of its
# software on equipment which is not supplied by Ensim.
#
# This script has to handle: psadmin, webppliance LX, webppliance LS
######################################################################

import sys, os
import re
import string

import ensimglobals
import ensimapplpath 
import cmdlnpopen
import svcdbpath

def restart_msg():
    sys.stderr.write("Please restart the appliance server to refresh the GUI.\n")    

def unhide_regular_service(svc):
    # unhide service from psadmin
    src = os.path.join(svcdbpath.HIDDEN_DIR, svcname)
    dest = os.path.join(svcdbpath.UNHIDDEN_DIR, svcname)
    if os.path.exists(src):
	os.rename(src, dest)
	if (os.path.exists(dest)) and (not os.path.exists(src)):
	    sys.stderr.write("Service %s unhidden.\n" % svcname)
            restart_msg()
	else:
	    sys.stderr.write("Failed to create file %s \n" % dest)
	    sys.exit(1)
    else:
	if os.path.exists(dest):
	    sys.stderr.write("Service %s unhidden\n" % svcname)
	else:
	    sys.stderr.write("Could not unhide service %s that is not owned by the appliance.\n" % svcname)
	    sys.exit(1)

def getInitScriptNames(srvName):
    all_lookupFile=["/usr/lib/opcenter/%s/%s.chkconfig" % (srvName, srvName)]
    # special case for apache 
    if srvName == "apache":
        all_lookupFile.append("/usr/lib/opcenter/apache13/%s.chkconfig" % (srvName))

    filelist=[] 
    for lookupFile in all_lookupFile:    
        if (os.access(lookupFile, os.F_OK)):
            lookupObj = open (lookupFile, "r")
            retList = lookupObj.readlines()
            lookupObj.close()

            # we need to remove all \n
            filelist.extend(map (lambda x: string.strip(x), retList))               
    return filelist

# returns (childOut, childErr, ret)
def enableFromRunLevel(scriptName):
    if scriptName:
        cmd1 = "/sbin/chkconfig --add %s" % scriptName
        cmd2 = "/sbin/chkconfig %s on" % scriptName

        out, err, ret = cmdlnpopen.cmd3 (cmd1)
        if err: sys.stderr.write(string.join(err, '\n'))
        if out: sys.stdout.write(string.join(out, '\n'))
        if ret: return ret
            
        out, err, ret = cmdlnpopen.cmd3 (cmd2)
        if err: sys.stderr.write(string.join(err, '\n'))
        if out: sys.stdout.write(string.join(out, '\n'))
        return ret        
    else:
        return 0

def startViaInitScript (scriptName):
    if scriptName:
        out, err, ret = cmdlnpopen.cmd3 ("/etc/rc.d/init.d/%s start" % scriptName)
        if err: sys.stderr.write(string.join(err, '\n'))
        if out: sys.stdout.write(string.join(out, '\n'))
        return ret
    return 0

if __name__ == '__main__':
    #check arguments
    if len(sys.argv) != 2:
	usage = "Usage: %s servicename" % sys.argv[0]
	sys.stderr.write(usage)
	sys.exit(1)

    svcname = sys.argv[1]

    if ensimglobals.PUBLISH_DIR == 'webhost':
	#webppliance
        import be_vherrordisp
	from vh3 import virthost
	services = virthost.get_ordered_service_list()
	if svcname in services:
	    status = virthost.unhide_service(svcname)
 
            if status == be_vherrordisp.CLIError.ERROR:
                sys.exit(1)
            else:
                restart_msg()
	else:
	    unhide_regular_service(svcname)
    else:
	# unhide service from psadmin
	unhide_regular_service(svcname)

    # now, we need to add the script from all run level
    # if applicable
    initScriptNameList = getInitScriptNames (svcname)
    if initScriptNameList:
        max_ret = 0
        for initScriptName in initScriptNameList:
            ret = enableFromRunLevel (initScriptName)
            max_ret = max(max_ret, ret)
            ret = startViaInitScript (initScriptName)
            max_ret = max(max_ret, ret)
        sys.exit(max_ret)

    sys.exit(0)
