import glob
import os
import sys

__author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2019 VMware, Inc. All rights reserved.'

LAUNCHER_PATTERN = "*launcher"
JAVA = "java"
VMWARE_JAVA_HOME = "VMWARE_JAVA_HOME"
JAVA_HOME_BIN = os.path.join(os.environ[VMWARE_JAVA_HOME], "bin")
JAVA_EXEC = os.path.join(JAVA_HOME_BIN, JAVA)
LAUNCHER_PATTERN_PATH = os.path.join(JAVA_HOME_BIN, LAUNCHER_PATTERN)

"""
Relink all the java launchers to point to $VMWARE_JAVA_HOME/bin/java

All the components are supposed to have their launchers (that are
basically 'java' executables) hardlinked to $VMWARE_JAVA_HOME/bin/java

After an in-place upgrade, it's possible that some of them are still
pointing to older java. This method will relink them to point to
the right Java. This is done by removing the offending launchers
and recreating them as a hardlink to $VMWARE_JAVA_HOME/bin/java

(This is part of move from Oracle JRE to Open JRE)

Returns:
    True or False, indicating the success or failure
"""


def relink_java_launchers():
    relink_successful = True

    print("Java launcher relink started")
    try:
        launchers = glob.glob(LAUNCHER_PATTERN_PATH)
        for launcher in launchers:
            try:
                if not os.path.samefile(JAVA_EXEC, launcher):
                    print("{0} not same as {1}, relinking...".format(
                        JAVA_EXEC, launcher))
                    os.unlink(launcher)
                    os.link(JAVA_EXEC, launcher)
            except Exception: #pylint: disable=W0703
                exc_type, exc_value, _ = sys.exc_info()
                print("Could not create a hardlink for {0} to {1}".format(
                    launcher, JAVA_EXEC))
                print("Relink failed {0} {1}".format(exc_type, exc_value))
                relink_successful = False
    except Exception:  #pylint: disable=W0703
        print("Could not read java launchers from {0}, with pattern {1}".format(
            JAVA_HOME_BIN, LAUNCHER_PATTERN))
        exc_type, exc_value, _ = sys.exc_info()
        print("glob.glob() failed {0} {1}".format(exc_type, exc_value))
        relink_successful = False
    return relink_successful


def validate_java_launchers():
    all_links_correct = True
    try:
        launchers = glob.glob(LAUNCHER_PATTERN_PATH)
        for launcher in launchers:
            if not os.path.samefile(JAVA_EXEC, launcher):
                print("{0} not same as {1}".format(JAVA_EXEC, launcher))
                all_links_correct = False
                # Don't break from loop, print all the mismatches
    except Exception: #pylint: disable=W0703
        exc_type, exc_value, _ = sys.exc_info()
        print("Error: {0} {1}".format(exc_type, exc_value))
        print("Cannot verify if all {0} point to {1}".format(
            LAUNCHER_PATTERN_PATH, JAVA_EXEC))
        all_links_correct = False

    return all_links_correct


if __name__ == "__main__":
    if relink_java_launchers():
        print("Java launcher relink complete")
    else:
        print("Java launcher relink failed")
    if validate_java_launchers():
        print("Java launcher relink verification successful")
    else:
        print("Java launcher relink verification failed")
