#!/usr/bin/env python3
from setup_utils import *
import os
import socket

# icat.server

def uninstall():
    app = actions.getAppName("icat.ear")
    if app: actions.undeploy(app)
    app = actions.getAppName("icat.server")
    if app: actions.undeploy(app)
    actions.unregisterDB("icat")
    actions.deleteJMSResource("jms/ICAT/Topic")
    actions.deleteJMSResource("jms/ICAT/Synch")
    actions.deleteJMSResource("jms/ICAT/log")
    
actions, arg, props = getActions("setup.properties", ["db.driver", "db.url", "db.username", "db.password"], binDir=True)

binDir = actions.getBinDir();
files = ["testicat", "icatadmin"]
prop_name = "run.properties"
prop_list = ["lifetimeMinutes", "rootUserNames", "authn.list", "notification.list", "log.list"]

if arg in ["CONFIGURE", "INSTALL"]: actions.configure(prop_name, prop_list) 
icatProperties = getProperties(prop_name, prop_list)

if arg in ["CONFIGURE", "INSTALL"]:
    actions.checkNoErrors()

if arg == "INSTALL":       
    for v in icatProperties["authn.list"].split():
        if "authn." + v + ".jndi" not in icatProperties and "authn." + v + ".url" not in icatProperties:
            abort ("authn.list included " + v + " but neither authn." + v + ".url nor authn." + v + ".jndi is not defined") 
    
    if icatProperties["notification.list"]:
        for v in icatProperties["notification.list"].split():
            if "notification." + v not in icatProperties:
                abort ("notification.list included " + v + " but notification." + v + " is not defined") 
    
    try:           
        uninstall()
        actions.registerDB("icat", props["db.driver"], props["db.url"], props["db.username"], props["db.password"])
        actions.createJMSResource("jakarta.jms.Topic", "jms/ICAT/Topic")
        actions.createJMSResource("jakarta.jms.Topic", "jms/ICAT/log")
            
        ovfiles = [[prop_name, "WEB-INF/classes"]]
        if os.path.exists("logback.xml"): ovfiles.append(["logback.xml", "WEB-INF/classes"])
        actions.deploy(deploymentorder=100, files=ovfiles, jmsTopicConnectionFactory=icatProperties.get("jms.topicConnectionFactory"), target=props.get("db.target"), logging=props.get("db.logging"))
        
        if not os.path.isdir(binDir): abort ("Please create directory " + binDir + " and try again.")
        for file in files:   
            if platform.system() != "Windows": os.chmod(file, 0o0755)    
            actions.installFile(file , binDir)
    except Exception as e:
        abort(str(e))
                
if arg == "UNINSTALL":        
    try:
        uninstall()
        for file in files:
            actions.removeFile(file, binDir) 
    except Exception as e:
        abort(str(e))
