#!/usr/bin/env python3
from __future__ import print_function
from setup_utils import *
import os
import re

# topcat


def uninstall():
    app = actions.getAppName("topcat")
    if app:
        actions.undeploy(app)

    app = actions.getAppName("datagateway-download-api")
    if app:
        actions.undeploy(app)

    actions.unregisterDB("topcat")
    actions.deleteMailResource("mail/topcat")


actions, arg, props = getActions("setup.properties", ["db.driver", "db.url", "db.username", "db.password"], binDir=True)

prop_name = "run.properties"
prop_list = []

binDir = actions.getBinDir()
# topcat_admin can't be used with the local Topcat server, as it needs topcat.json (which we have removed)
# Add topcat_admin_LILS, which can be used (but only with the local Topcat server)
# Add datagateway_admin, which can be used with DataGateway servers
binFiles = ["topcat_admin_LILS", "datagateway_admin"]

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

if arg == "INSTALL":
    try:
        uninstall()

        actions.registerDB("topcat", props["db.driver"], props["db.url"], props["db.username"], props["db.password"])

        # Only create the mail resource if all mail properties are defined.
        # NOTE: if the mail resource is not created, then mail.enable MUST be false in run.properties

        missing = [k for k in ("mail.host", "mail.user", "mail.from", "mail.property") if k not in props]

        if not missing:
            print("Creating mail resource...")
            actions.createMailResource("mail/topcat", props["mail.host"], props["mail.user"], props["mail.from"], props["mail.property"])
        else:
            print("Not creating mail resource as following is/are not set:", missing)

        files = [[prop_name, "WEB-INF/classes"]]

        if os.path.exists("logback.xml"):
            files.append(["logback.xml", "WEB-INF/classes"])

        actions.deploy(files=files, deploymentorder=140, target=props.get("db.target"), logging=props.get("db.logging"))

        # If there's no binDir, don't count it as a failure
        if os.path.isdir(binDir):
            for file in binFiles:
                if platform.system() != "Windows":
                    os.chmod(file, 0o0755)
                actions.installFile(file, binDir)
        else:
            print("Not copying executables to", binDir, "as it does not exist. Create the folder and re-run if required.")

    except Exception as e:
        abort(str(e))


if arg == "UNINSTALL":
    try:
        uninstall()
        if os.path.isdir(binDir):
            for file in binFiles:
                actions.removeFile(file, binDir)

    except Exception as e:
        abort(str(e))