#!/bin/bash

# Get the directory where the script is located
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
ABS_HOME=$SCRIPT_DIR/..
ABS_HOME=$(builtin cd $ABS_HOME; pwd)

# Configuration
PROPERTIES_FILE="${ABS_HOME}/config/application.properties"
TRIES=10
SLEEP_INTERVAL=30

# Function to read properties from application.properties
read_property() {
    local key=$1
    local value
    if [ -f "$PROPERTIES_FILE" ]; then
        value=$(grep "^${key}=" "$PROPERTIES_FILE" | cut -d'=' -f2- | tr -d '[:space:]')
        echo "$value"
    else
        echo "Error: Properties file not found at $PROPERTIES_FILE"
        exit 1
    fi
}

# Read configuration from properties file
PORT=$(read_property "management.server.port")
SSL_ENABLED=$(read_property "server.ssl.enabled")

# Determine protocol
if [ "$SSL_ENABLED" == "true" ]; then
    PROTOCOL="https"
else
    PROTOCOL="http"
fi

# Set host and health check URL
HOST=$(hostname)
HEALTH_URL="${PROTOCOL}://${HOST}:${PORT}/actuator/health"

# Function to make health check request
check_health() {
    local curl_opts="-s -w %{http_code} -k"

    response=$(curl $curl_opts "$HEALTH_URL")
    http_code=${response: -3}
    body=${response:0:${#response}-3}

    if [ "$http_code" == "200" ]; then
        if echo "$body" | grep -q '"status":"UP"'; then
            echo "Application is UP and healthy"
            return 0
        elif echo "$body" | grep -q '"status":"DOWN"'; then
            echo "Application is DOWN"
            return 2
        else
            echo "Unknown health status in response"
            return 3
        fi
    else
        echo "Health check failed with HTTP status $http_code"
        return 1
    fi
}

# Main loop
for ((i = 1; i <= TRIES; i++)); do
    echo "Try $i of $TRIES..."

    check_health
    status=$?

    case $status in
        0)
            echo "Application is healthy"
            exit 0
            ;;
        1)
            echo "HTTP request failed"
            ;;
        2)
            echo "Application reported DOWN status"
            ;;
        3)
            echo "Unknown health status"
            ;;
        *)
            echo "Unexpected error occurred"
            ;;
    esac

    if [ $i -lt $TRIES ]; then
        echo "Waiting ${SLEEP_INTERVAL} seconds before next try..."
        sleep $SLEEP_INTERVAL
    fi
done

echo "Application did not become healthy after $TRIES tries. Exiting."
exit 1

