#!/bin/bash
# function determineDockerState
#
# parameters
#   none
#
# return
#   0 - state of execution is for an installation
#   1 - state of execution is for an upgrade
#
# function will determine if there is already an docker container for the css image, thus an upgrade is needed else install

function determineDockerState
{
    logPoint "Checking Docker install/upgrade state"
    EXECUTION_STATE=${INSTALL}
    DOCKER_LS_RETURN_VAL=$(docker container inspect ${CONTAINER_NAME} 2> /dev/null)
    if [ $? -eq 0 ]
    then
        logPoint "Found an existing container with the name ${CONTAINER_NAME}. Running in UPGRADE mode."
        EXECUTION_STATE=${UPGRADE}
    else
        logPoint "Didn't find an existing container with the name ${CONTAINER_NAME}. Running in INSTALL mode."
    fi

    return ${EXECUTION_STATE}
}

# function getCSSVersionDocker
#
# parameters
#   CONTAINER_NAME - the name of the container that will be checked.
#
# return
# none
#
# function will get the version of the image for the container with the given name. Returns latest if no tag is provided

function getCSSVersionDocker
{
    IMAGE=$(docker container inspect ${CONTAINER_NAME} --format '{{index .Config.Image }}')
    IMAGE_NAME=$(echo ${IMAGE} | cut -f1 -d ":")
    TAG=$(echo ${IMAGE} | cut -f2 -d ":")
    if stringEquals ${IMAGE} ${IMAGE_NAME} || [ "${TAG,,}" = latest ]
    then
        #if the image version wasn't specified (used latest tag at the time) then find the sha of the image, which is unique for each fd version.
        TAG=$(docker container inspect ${CONTAINER_NAME} | grep Image | grep sha | cut -d: -f3 | cut -d\" -f1)
    fi
    CSS_VERSION=${TAG}

}

# function isDockerInstalled
#
# parameters
#   none
#
# return
#   0 - docker is not installed or not on the PATH
#   1 - docker is installed and on the PATH
#
# function will determine if docker is installed and on the PATH

function isDockerInstalled
{
    logPoint "Validating Docker is installed"

    RC=0
    if ! command -v docker &> /dev/null
    then
        generateFatalErrorMessage 131
        exit 1
    fi
    return ${RC}
}

# function isDockerDaemonRunning
#
# parameters
#   none
#
# return
#   0 - docker daemon is not running, or not able to be connected to
#   1 - docker daemon is running and able to be connected to
#
# function will determine if docker is installed and on the PATH

function isDockerDaemonRunning
{
    logPoint "Validating Docker Daemon is running"

    DOCKER_DAEMON_RUNNING=0
    ps -ef | grep dockerd | grep -v grep &> /dev/null
    PS_GREP_DOCKERD_VAL=$?
    variableEmpty ${PS_GREP_DOCKERD_VAL}
    if [ $? -eq 0 ] 
    then
        generateFatalErrorMessage 132
    else
        DOCKER_DAEMON_RUNNING=1
    fi

    return ${DOCKER_DAEMON_RUNNING}
}

# function pullDockerImage
#
# parameters
#   DESIRED_VERSION: The version of the docker container to be used in the pull/install
#
# return
#   0 - docker image pulled successfully
#   any other number - error occurred while pulling docker image
#
# function will determine if docker is installed and on the PATH

function pullDockerImage
{
    if [ "$DESIRED_VERSION" ]
    then
        logPoint "Pulling Docker image for ${DOCKER_REPO}cm/css_tcat:${DESIRED_VERSION}"
        DOCKER_PULL_VAL=$(docker pull ${DOCKER_REPO}cm/css_tcat:"${DESIRED_VERSION}")
    else
        logPoint "Pulling latest Docker image for ${DOCKER_REPO}cm/css_tcat"
        DOCKER_PULL_VAL=$(docker pull ${DOCKER_REPO}cm/css_tcat)
    fi

    return $?
}

# function deleteDockerContainer
#
# parameters
#   CONTAINER_NAME
#
# return
#   0 - docker container deleted
#   1 - docker container delete command encountered an error
#
# function will forcefully delete the docker container with the given container name

function deleteDockerContainer
{
    logPoint "Removing Docker container: ${CONTAINER_NAME}"
    DOCKER_DELETE_VAL=$(docker container rm ${CONTAINER_NAME} -f 2> /dev/null)
    return $?
}

# function startDockerContainer
#
# parameters
#   CONTAINER_NAME
#
# return
#   0 - docker container started
#   1 - docker container start command encountered an error
#
# function will start the docker container with the given container name

function startDockerContainer
{
    logPoint "Starting Docker container: ${CONTAINER_NAME}"
    DOCKER_START_VAL=$(docker start ${CONTAINER_NAME})
    return $?
}

# function stopDockerContainer
#
# parameters
#   CONTAINER_NAME
#
# return
#   0 - docker container stopped
#   1 - docker container stop command encountered an error
#
# function will stop the docker container with the given container name

function stopDockerContainer
{
    logPoint "Stopping Docker container: ${CONTAINER_NAME}"
    DOCKER_STOP_VAL=$(docker stop ${CONTAINER_NAME})
    return $?
}

# function runDockerContainer
#
# parameters
#   DATABASE_URL
#   FD_ADMIN_PWD
#   DB_TYPE
#   CSS_HOME
#   CONTAINER_NAME
#   CSS_PORT
#
# return
#   0 - docker container created and started
#   1 - docker container run command encountered an error
#
# function will execute the docker run command with the given parameters to create and start a docker container with CSS image

function runDockerContainer
{
    isOracleDatabase
    if [ $? -eq 0 ]
    then
        DB_TYPE=oracle
    else
        DB_TYPE=postgres
    fi
    if [ "$DESIRED_VERSION" ]
    then
        logPoint "Running Docker container with version ${DESIRED_VERSION}"
        DOCKER_RUN_VAL=$(docker run -d --name ${CONTAINER_NAME} -p ${CSS_PORT}:8081 -e TZ=${CONTAINER_TIMEZONE} -e FLEX_DB_URL=${DATABASE_URL} -e FD_ADMIN_PWD="${CSS_DB_PASSWORD}" -e dbtype=${DB_TYPE} -e MAX_ACTIVE_CONNECTIONS=100 -e MAX_IDLE_CONNECTIONS=100 -e MAX_WAIT_TIME_MILLIS=30000 -v ${CSS_HOME}:/dockervolume/css ${DOCKER_REPO}cm/css_tcat:"${DESIRED_VERSION}")
    else
        logPoint "Running Docker container with latest version"
        DOCKER_RUN_VAL=$(docker run -d --name ${CONTAINER_NAME} -p ${CSS_PORT}:8081 -e TZ=${CONTAINER_TIMEZONE} -e FLEX_DB_URL=${DATABASE_URL} -e FD_ADMIN_PWD="${CSS_DB_PASSWORD}" -e dbtype=${DB_TYPE} -e MAX_ACTIVE_CONNECTIONS=100 -e MAX_IDLE_CONNECTIONS=100 -e MAX_WAIT_TIME_MILLIS=30000 -v ${CSS_HOME}:/dockervolume/css ${DOCKER_REPO}cm/css_tcat)
    fi
    return $?
}

function dockerPrereq
{
    isDockerDaemonRunning
    isDockerInstalled

    #The docker volume requires these to be constant values.
    if [ "${WORKING_DIRECTORY}" != "${CSS_HOME}/application" ]
    then
        WORKING_DIRECTORY="${CSS_HOME}/application"
        logPoint "Overriding value for WORKING_DIRECTORY to ${WORKING_DIRECTORY}"
    fi
    
    if [ "${ARTIFACT_REPOSITORY_DIRECTORY}" != "${CSS_HOME}/artifacts" ]
    then
        ARTIFACT_REPOSITORY_DIRECTORY=${CSS_HOME}/artifacts
        logPoint "Overriding value for ARTIFACT_REPOSITORY_DIRECTORY to ${ARTIFACT_REPOSITORY_DIRECTORY}"
    fi
    
}