#!/bin/bash

PATH=sitemap.xml


#######################################
#
# common.sh
#
#######################################

GREEN='\033[0;32m'
BLUE='\033[0;94m'
LIGHT_BLUE='\033[0;34m'
YELLOW='\033[0;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

#######################################
# Check if command exists.
# Globals:
#   None
# Arguments:
#   None
# Returns:
#   0 if command exists
#######################################
commandExists() {
    command -v "$@" > /dev/null 2>&1
}

#######################################
# Check if replicated 1.2 is installed
# Globals:
#   None
# Arguments:
#   None
# Returns:
#   0 if replicated 1.2 is installed
#######################################
replicated12Installed() {
    commandExists replicated && replicated --version | grep -q "Replicated version 1\.2"
}

#######################################
# Check if replicated 2.0 is installed
# Globals:
#   None
# Arguments:
#   None
# Returns:
#   0 if replicated 2.0 is installed
#######################################
replicated2Installed() {
    commandExists /usr/local/bin/replicatedctl && /usr/local/bin/replicatedctl version >/dev/null 2>&1
}

#######################################
# Returns replicated 2.0 version
# Globals:
#   None
# Arguments:
#   None
# Returns:
#   INSTALLED_REPLICATED_VERSION
#######################################
replicated2Version() {
    if replicated2Installed; then
        INSTALLED_REPLICATED_VERSION="$(/usr/local/bin/replicatedctl version --quiet)"
    else
        INSTALLED_REPLICATED_VERSION=""
    fi
}

#######################################
# Returns 0 if replicated will downgrade
# Globals:
#   None
# Arguments:
#   Next replicated version
# Returns:
#   0 if replicated version is less than current
#   1 if replicated version is greater than or equal to current
#######################################
isReplicatedDowngrade() {
    if ! replicated2Installed; then
        return 1
    fi

    replicated2Version
    semverCompare "$1" "$INSTALLED_REPLICATED_VERSION"
    if [ "$SEMVER_COMPARE_RESULT" -lt "0" ]; then
        return 0
    fi
    return 1
}

#######################################
# Gets curl or wget depending if cmd exits.
# Globals:
#   PROXY_ADDRESS
# Arguments:
#   None
# Returns:
#   URLGET_CMD
#######################################
URLGET_CMD=
getUrlCmd() {
    if commandExists "curl"; then
        URLGET_CMD="curl -sSL"
        if [ -n "$PROXY_ADDRESS" ]; then
            URLGET_CMD=$URLGET_CMD" -x $PROXY_ADDRESS"
        fi
    else
        URLGET_CMD="wget -qO-"
    fi
}

#######################################
# Generates a 32 char unique id.
# Globals:
#   None
# Arguments:
#   None
# Returns:
#   GUID_RESULT
#######################################
getGuid() {
    GUID_RESULT="$(head -c 128 /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1)"
}

#######################################
# performs in-place sed substitution with escapting of inputs (http://stackoverflow.com/a/10467453/5344799)
# Globals:
#   None
# Arguments:
#   None
# Returns:
#   None
#######################################
safesed() {
    sed -i "s/$(echo $1 | sed -e 's/\([[\/.*]\|\]\)/\\&/g')/$(echo $2 | sed -e 's/[\/&]/\\&/g')/g" $3
}

#######################################
# Parses a semantic version string
# Globals:
#   None
# Arguments:
#   Version
# Returns:
#   major, minor, patch
#######################################
semverParse() {
    major="${1%%.*}"
    minor="${1#$major.}"
    minor="${minor%%.*}"
    patch="${1#$major.$minor.}"
    patch="${patch%%[-.]*}"
}

#######################################
# Compare two semvers.
# Returns -1 if A lt B, 0 if eq, 1 A gt B.
# Globals:
#   None
# Arguments:
#   Sem Version A
#   Sem Version B
# Returns:
#   SEMVER_COMPARE_RESULT
#######################################
SEMVER_COMPARE_RESULT=
semverCompare() {
    semverParse "$1"
    _a_major="${major:-0}"
    _a_minor="${minor:-0}"
    _a_patch="${patch:-0}"
    semverParse "$2"
    _b_major="${major:-0}"
    _b_minor="${minor:-0}"
    _b_patch="${patch:-0}"
    if [ "$_a_major" -lt "$_b_major" ]; then
        SEMVER_COMPARE_RESULT=-1
        return
    fi
    if [ "$_a_major" -gt "$_b_major" ]; then
        SEMVER_COMPARE_RESULT=1
        return
    fi
    if [ "$_a_minor" -lt "$_b_minor" ]; then
        SEMVER_COMPARE_RESULT=-1
        return
    fi
    if [ "$_a_minor" -gt "$_b_minor" ]; then
        SEMVER_COMPARE_RESULT=1
        return
    fi
    if [ "$_a_patch" -lt "$_b_patch" ]; then
        SEMVER_COMPARE_RESULT=-1
        return
    fi
    if [ "$_a_patch" -gt "$_b_patch" ]; then
        SEMVER_COMPARE_RESULT=1
        return
    fi
    SEMVER_COMPARE_RESULT=0
}

#######################################
# Inserts a parameter into a json file. If the file does not exist, creates it. If the parameter is already set, replaces it.
# Globals:
#   None
# Arguments:
#   path, parameter name, value
# Returns:
#   None
#######################################
insertOrReplaceJsonParam() {
    if ! [ -f "$1" ]; then
        # If settings file does not exist
        mkdir -p "$(dirname "$1")"
        echo "{\"$2\": \"$3\"}" > "$1"
    else
        # Settings file exists
        if grep -q -E "\"$2\" *: *\"[^\"]*\"" "$1"; then
            # If settings file contains named setting, replace it
            sed -i -e "s/\"$2\" *: *\"[^\"]*\"/\"$2\": \"$3\"/g" "$1"
        else
            # Insert into settings file (with proper commas)
            if [ $(wc -c <"$1") -ge 5 ]; then
                # File long enough to actually have an entry, insert "name": "value",\n after first {
                _commonJsonReplaceTmp="$(awk "NR==1,/^{/{sub(/^{/, \"{\\\"$2\\\": \\\"$3\\\", \")} 1" "$1")"
                echo "$_commonJsonReplaceTmp" > "$1"
            else
                # file not long enough to actually have contents, replace wholesale
                echo "{\"$2\": \"$3\"}" > "$1"
            fi
        fi
    fi
}

######################################
# Inserts a string array of length 1 into a json file. Fails if key is found in file.
# Globals:
#   None
# Arguments:
#   path, key, value[0]
# Returns:
#   1 if there are errors
######################################
insertJSONArray() {
	if ! [ -f "$1" ] || [ $(wc -c <"$1") -lt 5 ]; then
        mkdir -p "$(dirname "$1")"
		cat > $1 <<EOF
{
  "$2": ["$3"]
}
EOF
		return 0
	fi

	if grep -q "$2" "$1"; then
		return 1
	fi

	_commonJsonReplaceTmp="$(awk "NR==1,/^{/{sub(/^{/, \"{\\\"$2\\\": [\\\"$3\\\"], \")} 1" "$1")"
	echo "$_commonJsonReplaceTmp" > "$1"
	return 0
}

#######################################
# Splits an address in the format "host:port".
# Globals:
#   None
# Arguments:
#   address
# Returns:
#   HOST
#   PORT
#######################################
splitHostPort() {
    oIFS="$IFS"; IFS=":" read -r HOST PORT <<< "$1"; IFS="$oIFS"
}

#######################################
# Checks if Docker is installed
# Globals:
#   None
# Arguments:
#   None
# Returns:
#   0 if Docker is installed
#######################################
isDockerInstalled() {
    commandExists "docker" && ps aux | grep -q '[d]ockerd'
}

#######################################
# Creates and sets REPLICATED_TEMP_DIR variable if not set.
# Globals:
#   None
# Arguments:
#   adNonedress
# Returns:
#   REPLICATED_TEMP_DIR
#######################################
maybeCreateTempDir() {
    if [ -z "$REPLICATED_TEMP_DIR" ]; then
        REPLICATED_TEMP_DIR="$(mktemp -d --suffix=replicated)"
    fi
}

#######################################
# Prints 404 with associated bad path.
# Globals:
#   PATH
# Arguments:
#   None
# Returns:
#   None
#######################################
printf "${RED}
            404: Not Found
            There was an error processing the request to generate the installation script

                Request path: $PATH

            Please visit https://help.replicated.com/ for installation guides and documentation${NC}\n\n\
"

exit 1