#!/bin/sh

# Check valid URL path
# 1 - Return Result
# 2 - URL
checkValidUrl()
{
    RESULT_VALID_URL="$1"
    URL=`echo "$2" | tr [:upper:] [:lower:]`

    if [ `echo $URL | cut -c1-5` = "http:" -o `echo $URL | cut -c1-6` = "https:" ]; then
        eval $RESULT_VALID_URL="Y"
    else
        eval $RESULT_VALID_URL="N"
    fi
}

# Extract server address from name in format obm-nix-%PORT%-%HOST_NAME%-%PROTOCOL%-%OWNER_ID%.sh, where %PROTOCOL% is "http"/"https"
# 1 - Return HostAddr
# 2 - Return OwnerID
# 3 - Name
parseHostAddrFromName()
{
    RESULT_HOST_ADDR="$1"
    RESULT_OWNER_ID="$2"
    # add prefix here to avoid failure case "-abc", prefix will be abandoned below
    NAME=`basename "prefix$3"`

    eval $RESULT_HOST_ADDR=""
    eval $RESULT_OWNER_ID=""

    PROTOCOL=""
    SUFFIX_NAME=""
    # remove file ext
    NAME=`echo "$NAME" | sed "s|\.[^\.]*$||"`

    while true; do
        # sed "s|^[^-]*$||": replace whole string with empty if whole string is without '-'
        if [ -z "`echo $NAME | sed \"s|^[^-]*$||\"`" ]; then
            break;
        fi
        # get suffix
        SUFFIX=`echo "$NAME" | sed "s|^.*-||"`
        # remove suffix
        NAME=`echo "$NAME" | sed "s|-[^-]*$||"`
        if [ ! -z "`echo $SUFFIX | grep \"^https\"`" ]; then
            PROTOCOL="https"
            break;
        fi
        if [ ! -z "`echo $SUFFIX | grep \"^http\"`" ]; then
            PROTOCOL="http"
            break;
        fi
        if [ -z "$SUFFIX_NAME" ]; then
            SUFFIX_NAME="$SUFFIX"
        else
            SUFFIX_NAME="$SUFFIX-$SUFFIX_NAME"
        fi
    done

    if [ ! -z "$PROTOCOL" ]; then
        # remove prefix
        NAME=`echo "$NAME" | sed "s|[^-]*-||"`
        while true; do
            # sed "s|^[^-]*$||": replace whole string with empty if whole string is without '-'
            if [ -z "`echo $NAME | sed \"s|^[^-]*$||\"`" ]; then
                break;
            fi
            # PORT must be either a number or empty
            PORT=`echo "$NAME" | cut -d'-' -f1 | sed "s|.*[^0-9].*||"`
            NAME=`echo "$NAME" | sed "s|[^-]*-||"`
            # check if PORT is valid
            if [ ! -z "$PORT" ] && [ "$PORT" -le 65535 ] && [ "$PORT" -ge 0 ]; then
                if [ ! -z "$NAME" ]; then
                    eval "$RESULT_HOST_ADDR=\"$PROTOCOL://$NAME:$PORT\""
                fi
                break;
            fi
        done
    fi
    if [ ! -z "$SUFFIX_NAME" ]; then
        # remove character 'O' and string following it
        # this is not number "zero", it is a upper case 'o'
        SUFFIX_NAME=`echo "$SUFFIX_NAME" | sed "s|O[^O]*$||"`
        eval "$RESULT_OWNER_ID=\"$SUFFIX_NAME\""
    fi
}

# Download and setup prepackaged components
# 1 - Return Result
# 2 - URL
# 3 - File Name
# 4 - URL Argu
# 5 - Destination
# 6 - Package Type
downloadAndSetupComponent()
{
    SETUP_RESULT="$1"
    SOURCE_URL_HOME="$2"
    SOURCE_FILE="$3"
    SOURCE_URL_ARGU="$4"
    DESTINATION_DIR="$5"
    PKG_TYPE="$6"

    if [ ! -z "$SOURCE_URL_ARGU" ]; then
        DOWNLOAD_URL="$SOURCE_URL_HOME/$SOURCE_FILE?$SOURCE_URL_ARGU"
    else
        DOWNLOAD_URL="$SOURCE_URL_HOME/$SOURCE_FILE"
    fi
    CURRENT_DIR=`pwd`
    if [ "$PKG_TYPE" = "jvm" ] ; then
        TARGET_DIR="$DESTINATION_DIR/jvm"
    else
        TARGET_DIR="$DESTINATION_DIR"
    fi

    echo "Downloading file... $SOURCE_FILE"
    if [ "$MY_PLATFORM" = "solaris" ]; then
        /usr/sfw/bin/wget --no-check-certificate "$DOWNLOAD_URL" -O "$SOURCE_FILE"
    else
        curl -k "$DOWNLOAD_URL" -o "$SOURCE_FILE"
    fi
    if [ -f "$SOURCE_FILE" ]; then
        echo "Download file completed"
        if [ ! -d "$TARGET_DIR" ]; then
            mkdir "$TARGET_DIR"
        fi
        echo "Untar component file to $TARGET_DIR"
        if [ "$MY_PLATFORM" = "solaris" ] ; then
            cd "$TARGET_DIR"
            gzip -cdf "$CURRENT_DIR/$SOURCE_FILE" | /usr/sfw/bin/gtar xf - > /dev/null
            cd "$CURRENT_DIR"
        elif [ "$MY_PLATFORM" = "others" ] ; then
            tar -xzf "$SOURCE_FILE" -C "$TARGET_DIR" > /dev/null
        fi
        rm "$SOURCE_FILE"
        eval $SETUP_RESULT="Y"
    else
        echo "Fail to download file from URL $DOWNLOAD_URL"
        eval $SETUP_RESULT="N"
    fi
}

# Verify and setup prepackaged components
# 1 - Return Result
# 2 - Source
# 3 - File Name
# 4 - Destination
# 5 - Package Type
verifyAndSetupComponent()
{
    SETUP_RESULT="$1"
    SOURCE_DIR="$2"
    SOURCE_FILE="$3"
    DESTINATION_DIR="$4"
    PKG_TYPE="$5"

    CURRENT_DIR=`pwd`
    if [ "$PKG_TYPE" = "jvm" ] ; then
        TARGET_DIR="$DESTINATION_DIR/jvm"
    else
        TARGET_DIR="$DESTINATION_DIR"
    fi

    if [ -f "$SOURCE_DIR/$SOURCE_FILE" ]; then
        if [ ! -d "$TARGET_DIR" ]; then
            mkdir "$TARGET_DIR"
        fi
        echo "Untar $SOURCE_FILE to $TARGET_DIR"
        if [ "$MY_PLATFORM" = "solaris" ] ; then
            cd "$TARGET_DIR"
            gzip -cdf "$SOURCE_DIR/$SOURCE_FILE" | /usr/sfw/bin/gtar xf - > /dev/null
            cd "$CURRENT_DIR"
        elif [ "$MY_PLATFORM" = "others" ] ; then
            tar -xzf "$SOURCE_DIR/$SOURCE_FILE" -C "$TARGET_DIR" > /dev/null
        fi
        eval $SETUP_RESULT="Y"
    else
        echo "$SOURCE_FILE not exists"
        eval $SETUP_RESULT="N"
    fi
}

# Prepare prepackaged components
# 1 - Return Result
preparePackagedComponents()
{
    PREPARE_RESULT="$1"
    eval $PREPARE_RESULT="N"

    RESULT_JVM_HOME="$2"
    eval $RESULT_JVM_HOME="Y"

    VERSION="8.7.0.0"
    JVM_URL="obs/download/jvm"
    COMPONENT_URL="obs/download/component"
    URL_ARGU=""
    HOST_ADDR=""
    OWNER_ID=""

    DOWNLOAD_PGK="Y"
    # Parse host address
    parseHostAddrFromName HOST_ADDR OWNER_ID "$RESTORER"
    if [ -z "$HOST_ADDR" ] && [ -d "$PKG_DIR" ]; then
        echo "Using package in $PKG_DIR"
        DOWNLOAD_PGK="N"
    fi

    if [ "$DOWNLOAD_PGK" = "N" ] ; then
        if [ ! -f "$PKG_DIR/version.txt" ]; then
            echo "Package version file not exists"
            return
        fi
        PKG_VERSION=`cat "$PKG_DIR/version.txt"`
        echo "Package version: $PKG_VERSION"
        MIN_VERSION="$(printf "$VERSION\n$PKG_VERSION\n" | sort -t. -k 1,1n -k 2,2n -k 3,3n -k 4,4n | head -n1)"
        if [ "$MIN_VERSION" = "$VERSION" ] && [ "$PKG_VERSION" != "$VERSION" ]; then
            echo "Package version does not match with installer version: $VERSION"
            return
        fi
    else
        if [ -z "$HOST_ADDR" ]; then
            echo "Host address is not defined"
            return
        fi
        if [ -z "$OWNER_ID" ]; then
            echo "Owner ID is not defined"
            return
        fi
        IS_VALID_URL="N"
        checkValidUrl IS_VALID_URL "$HOST_ADDR"
        if [ "$IS_VALID_URL" = "N" ]; then
            echo "Invalid host address - $HOST_ADDR"
            return
        fi
        echo "Host address: $HOST_ADDR"

        # Check jvm url
        if [ ! -z "$JVM_URL" ] ; then
            IS_VALID_URL="N"
            checkValidUrl IS_VALID_URL "$JVM_URL"
            if [ "$IS_VALID_URL" = "N" ]; then
                JVM_URL="$HOST_ADDR/$JVM_URL"
            fi
        fi
        if [ -z "$JVM_URL" ] ; then
            echo "JVM package's URL is not defined"
            return
        fi

        # Check component url
        if [ ! -z "$COMPONENT_URL" ] ; then
            IS_VALID_URL="N"
            checkValidUrl IS_VALID_URL "$COMPONENT_URL"
            if [ "$IS_VALID_URL" = "N" ]; then
                COMPONENT_URL="$HOST_ADDR/$COMPONENT_URL"
            fi
        fi
        if [ -z "$COMPONENT_URL" ] ; then
            echo "Component package's URL is not defined"
            return
        fi

        URL_VERSION_ARGU_TAG="version"
        URL_OWNER_ID_ARGU_TAG="ownerid"
        if [ "$URL_VERSION_ARGU_TAG" != "" ] && [ "$URL_OWNER_ID_ARGU_TAG" != "" ]; then
          URL_ARGU="$URL_VERSION_ARGU_TAG=$VERSION&$URL_OWNER_ID_ARGU_TAG=$OWNER_ID"
        elif [ "$URL_OWNER_ID_ARGU_TAG" != "" ]; then
          URL_ARGU="$URL_OWNER_ID_ARGU_TAG=$OWNER_ID"
        elif [ "$URL_VERSION_ARGU_TAG" != "" ]; then
          URL_ARGU="$URL_VERSION_ARGU_TAG=$VERSION"
        fi
    fi

    # Prepare jvm
    PKG_JVM_FILE=""
    case "`uname`" in
        Linux*)
            if [ "$MY_ARCH" = "64" ]; then
                PKG_JVM_FILE="jre-std-linux-amd64.tar.gz"
            elif [ "$MY_ARCH" = "32" ]; then
                PKG_JVM_FILE="jre-std-linux-x86-586.tar.gz"
            fi
            ;;
        *)
            ;;
    esac
    if [ -z "$PKG_JVM_FILE" ]; then
        echo "No JVM package is defined"
        eval $RESULT_JVM_HOME="N"
    else
        for word in $PKG_JVM_FILE
        do
            if [ "$DOWNLOAD_PGK" = "N" ] ; then
                verifyAndSetupComponent SETUP_RESULT "$PKG_DIR" "$word" "$APP_TMP" "jvm"
            else
                downloadAndSetupComponent SETUP_RESULT "$JVM_URL" "$word" "$URL_ARGU" "$APP_TMP" "jvm"
            fi
            if [ "$SETUP_RESULT" = "N" ] ; then
                echo "Failed to prepare JVM files."
                return
            fi
        done
    fi

    # Prepare other components
    PKG_COMPONENT_FILE=""
    if [ "$MY_ARCH" = "64" ]; then
        PKG_COMPONENT_FILE="app-common.tar.gz app-native-nix-x64.tar.gz app-nix-obm.tar.gz aua-common.tar.gz aua-native-nix-x64.tar.gz aua-nix-obm.tar.gz util-common.tar.gz util-nix-obm.tar.gz properties-common.tar.gz app-inst-nix-obm.tar.gz aua-inst-nix-obm.tar.gz"
    elif [ "$MY_ARCH" = "32" ]; then
        PKG_COMPONENT_FILE="app-common.tar.gz app-native-nix-x86.tar.gz app-nix-obm.tar.gz aua-common.tar.gz aua-native-nix-x86.tar.gz aua-nix-obm.tar.gz util-common.tar.gz util-nix-obm.tar.gz properties-common.tar.gz app-inst-nix-obm.tar.gz aua-inst-nix-obm.tar.gz"
    else
        PKG_COMPONENT_FILE="app-common.tar.gz app-native-nix-others.tar.gz app-nix-obm.tar.gz aua-common.tar.gz aua-native-nix-others.tar.gz aua-nix-obm.tar.gz util-common.tar.gz util-nix-obm.tar.gz properties-common.tar.gz app-inst-nix-obm.tar.gz aua-inst-nix-obm.tar.gz"
    fi
    if [ -z "$PKG_COMPONENT_FILE" ]; then
        echo "No component package is defined"
    else
        for word in $PKG_COMPONENT_FILE
        do
            if [ "$DOWNLOAD_PGK" = "N" ] ; then
                verifyAndSetupComponent SETUP_RESULT "$PKG_DIR" "$word" "$APP_TMP" "others"
            else
                downloadAndSetupComponent SETUP_RESULT "$COMPONENT_URL" "$word" "$URL_ARGU" "$APP_TMP" "others"
            fi
            if [ "$SETUP_RESULT" = "N" ] ; then
                echo "Failed to prepare component files."
                return
            fi
        done
    fi

    if [ "$DOWNLOAD_PGK" = "N" ] ; then
        rm -rf "$PKG_DIR"
    fi
    eval $PREPARE_RESULT="Y"
}

# ---------------------------------
# Initialize
cd `dirname "$0"`

RESTORER="$0"
EXEC_HOME=`pwd`
APP_HOME=$EXEC_HOME/RestoreWizard
APP_BIN=$APP_HOME/bin
TIMESTAMP_DIR=`date '+%y%m%d%H%M%S'`
APP_TMP="/tmp/_obm.$TIMESTAMP_DIR"
PKG_DIR="$EXEC_HOME/app.pkg"

# get arch of this system
MY_PLATFORM=""
case "`uname`" in
    Solaris* | SunOS*)
        MY_PLATFORM="solaris"
        case "`isainfo -b`" in
            32)
                MY_ARCH="32"
                ;;
            64)
                MY_ARCH="64"
                ;;
            *)
                MY_ARCH="Others"
                ;;
        esac
        ;;
    *)
        MY_PLATFORM="others"
        case "`uname -m`" in
            i[3-6]86)
                MY_ARCH="32"
                ;;
            x86_64 | amd64)
                MY_ARCH="64"
                ;;
            *)
                MY_ARCH="Others"
                ;;
        esac
        ;;
esac

# Print Logging Message Header
echo "Log Time: `date`"

# 22765: Verify if GNU Libc version is supported for Linux
# 26508: Support Debian
# DIST=`grep DISTRIB_ID /etc/*-release | awk -F '=' '{print $2}'`
DIST=`grep -w ID /etc/os-release | awk -F '=' '{print $2}'`
# if [ "$DIST" != "Ubuntu" ]; then
if [ "$DIST" != "ubuntu" -a "$DIST" != "debian" ]; then
    case "`uname`" in
        Linux*)
            MINIMUM_SUPPORTED_GLIBC_VERSION=2.14 # The GLibc supported version is defined in APP v8.0 onwards
            GLIBC_VERSION=`ldd --version | awk '/ldd/{print $NF}'`
            GLIBC_VERSION="${GLIBC_VERSION/./}"
            GLIBC_VERSION="${GLIBC_VERSION//.*/}"
            if [ $GLIBC_VERSION -lt 214 ]
            then
                echo "The GNU LIBC version is less than required \"$MINIMUM_SUPPORTED_GLIBC_VERSION\". Exit \""`basename "$0"`"\" now."
                exit 1
            fi
            ;;
        *)
            ;;
    esac
fi

# Prepare packaged components
if [ -d "$APP_TMP" ]; then
    rm -rf "$APP_TMP"
fi
mkdir "$APP_TMP"

preparePackagedComponents RESULT JVM_HOME_RESULT
if [ "$RESULT" = "N" ] ; then
    echo "Error in preparing files, installer will terminate"
    rm -rf "$APP_TMP"
    exit 1
fi

# Move packaged components
if [ ! -d "$APP_HOME" ]; then
    mkdir "$APP_HOME"
fi
mv "$APP_TMP"/* "$APP_HOME"
rm -rf "$APP_TMP"

# Verify if JVM home exist
cd "$APP_HOME"
JVM_HOME=$APP_HOME/jvm
if [ "$JVM_HOME_RESULT" = "N" ]; then
    USER_JVM_HOME=""
    echo "Please enter your java 1.8 home: "
    read USER_JVM_HOME
    if [ -z "$USER_JVM_HOME" ]; then
        echo "Invalid java home!"
        exit 1
    fi
    if [ ! -d "$USER_JVM_HOME" ]; then
        echo "$USER_JVM_HOME does not exist!"
        exit 1
    fi
    JVM_SECURITY="$APP_HOME/util/jvm/lib/security"
    if [ -d "$JVM_SECURITY" ]; then
        echo "Copy java 1.8 from $USER_JVM_HOME"
            if [ ! -d "$JVM_HOME" ]; then
                cp -rf "$USER_JVM_HOME" "$JVM_HOME"
            else
                cp -rf $USER_JVM_HOME/* $JVM_HOME
            fi
        cp -rf $JVM_SECURITY/* $JVM_HOME/lib/security
    else
        echo "Create symbolic link from $USER_JVM_HOME"
        ln -sf "$USER_JVM_HOME" "$JVM_HOME"
    fi
fi

# Configure Application
CONFIG_SCRIPT="$APP_BIN/config.sh"
if [ ! -f "$CONFIG_SCRIPT" ]; then
    echo "Config script not exist"
    rm -rf "$APP_HOME"
    exit 1
fi
echo "Configure Application Path: $APP_HOME"
sh "$CONFIG_SCRIPT"

[ $? -ne 0 ] && echo "" && echo "Error is found during \"config\"." && rm -rf "$APP_HOME" && exit 1

# Verify if run script exist
RUN_SCRIPT="$APP_BIN/RunRestore.sh"
if [ ! -f "$RUN_SCRIPT" ]; then
    echo "Run script not exist"
    rm -rf "$APP_HOME"
    exit 1
fi
sh "$RUN_SCRIPT"

# Exit
cd "$EXEC_HOME"
rm -rf "$APP_HOME"
echo "Done"
exit 0
