#!/bin/bash

INSTALL_SYMLINK="/opt/waratek"
readonly FILE_PREFIX="wdep"
readonly MENU_FILE="/tmp/${FILE_PREFIX}.menu"
readonly PRODUCT_LIST_FILE="/tmp/${FILE_PREFIX}.productlist"

wdep_clearfiles()
{
    rm /tmp/${FILE_PREFIX}*
}

wdep_displaymenu()
{
    local counter=1

    if [ -L "${INSTALL_SYMLINK}" ]; then
        # Link exists so there is an active version installed
        ACTIVE_PROD_PATH="$(readlink ${INSTALL_SYMLINK})"
    elif [ -d "${INSTALL_SYMLINK}" ]; then
        # Expected install location is an existing physical directory, must prompt for a different location
        echo -e "\t\t\t The default install location [/opt/waratek] already exists and is not a symlink"
        read -p $'\t\t\t Please specify an alternative install location [/opt/wtk]: ' USER_LOCATION_CHOICE
        INSTALL_SYMLINK=${USER_LOCATION_CHOICE:-/opt/wtk}
        if [ -L "${INSTALL_SYMLINK}" ]; then
            # Specified link exists so there is an active version installed
            ACTIVE_PROD_PATH="$(readlink ${INSTALL_SYMLINK})"
        elif [ -d "${INSTALL_SYMLINK}" ]; then
            # User has erroneously specified an existing physical directory to use as the install symlink
            echo "[ERROR] ${INSTALL_SYMLINK} is an existing physical directory. Please re-run the script and specify a non-existing location"
            exit 1
        else
            ACTIVE_PROD_PATH="$(readlink ${INSTALL_SYMLINK})"
        fi
    else
        # No symlink so no active version but at least one (this release!) non-active version
        ACTIVE_PROD_PATH=""
    fi

    # Get the list of products extracted under /opt
    INSTALLED_LIST=$(find /opt -type d -name "waratek-java*" | sort)

    # Generate the interactive menu
    echo -e "\t\t\t Available Waratek Products:"

    for FULL_PROD_PATH in ${INSTALLED_LIST}
    do
        if [ "${FULL_PROD_PATH}" = "${ACTIVE_PROD_PATH}" ]; then
            ACTIVE_VER="[active]"
        else
            ACTIVE_VER=""
        fi
        # Parse the full product path to get the product name & version.
        local PROD_NAME=$(echo ${FULL_PROD_PATH} | cut -d/ -f3 | cut -d- -f1-3)
        local PROD_SEMVER=$(echo ${FULL_PROD_PATH} | cut -d/ -f3 | cut -d- -f4)
        echo -e "\t\t\t [${counter}] ${PROD_NAME} ${PROD_SEMVER} ${ACTIVE_VER}" | tee -a ${MENU_FILE}
        echo "${counter}:${FULL_PROD_PATH}:${ACTIVE_VER}" >> ${PRODUCT_LIST_FILE}
        echo ${counter} > /tmp/${FILE_PREFIX}.count
        counter=$(expr ${counter} + 1)
    done

    echo -e "\t\t\t [0] Exit/Stop"
    echo -e "\t\t\t Choose the Product Version you wish to use [0 to exit]: \c"
    read USER_CHOICE
}

wdep_symlink()
{
    # Check if $2 is a symbolic link and if so, remove it
    [ -L $2 ] && rm -f $2

    # Create symlink between $1 and $2
    ln -s $1 $2
}

wdep_switch()
{
    local PRODUCT_CHOICE=$1
    local ACTIVE_PROD_PATH=$2

    # Get selected Product Path based on the user's choice
    PRODUCT_LIST=$(cat ${PRODUCT_LIST_FILE})
    for PRODUCT_LINE in ${PRODUCT_LIST}
    do
        NUM=$(echo ${PRODUCT_LINE} | cut -d: -f1)

        if [ "${NUM}" = "${PRODUCT_CHOICE}" ]; then
            local PROD_TO_USE=$(echo ${PRODUCT_LINE} | cut -d: -f2)
            break
        fi
    done

    if [ "${ACTIVE_PROD_PATH}" = "${PROD_TO_USE}" ]; then
        echo "[INFO] The chosen product is already active."
    elif [ -z ${ACTIVE_PROD_PATH} ]; then
        # No product is active so set symlink without any file copying
        wdep_symlink ${PROD_TO_USE} ${INSTALL_SYMLINK}
    else
        # Copy over config from active product to product the user has chosen
        cp -rf ${ACTIVE_PROD_PATH}/conf* ${PROD_TO_USE}/

        # Switch the symlink to the product the user has chosen
        wdep_symlink ${PROD_TO_USE} ${INSTALL_SYMLINK}
    fi

    echo "[INFO] ${PROD_TO_USE} is now the active product."
}


# The script must run as sudo (or root)
if [ "$EUID" -ne 0 ]; then
    echo "[INFO] Please run this script as: sudo $0 (or as root user if sudo is unavailable)."
    exit 1
fi

while true
do
    wdep_displaymenu

    # Set the counter to the number (1 or more) of deployed Waratek releases that have been found.
    counter=$(cat /tmp/${FILE_PREFIX}.count)

    case ${USER_CHOICE} in
        [1-${counter}])
            echo "You chose ${USER_CHOICE}"
            wdep_switch ${USER_CHOICE} ${ACTIVE_PROD_PATH}
            echo "Press any key to return to the menu"
            read anykey
            ;;
        0)
            wdep_clearfiles
            exit 0
            ;;
        *)
            echo "[WARNING] Invalid choice! Please select a number.. "
            echo "Press any key to return to the menu"
            read anykey
            ;;
    esac
done
