#!/bin/bash

# Arguments passed from Keepalived: 
# $1 = Primary Service Name (e.g., "gitea")
# $2 = Dependency Name (e.g., "postgres") - Optional

SERVICE_LIST="$1"
DEPENDENCY="$2"

# Function to check container status
check_container() {
    local container_name=$1
    if [ -z "$container_name" ]; then return 0; fi

    # Check if container is running
    # We use --filter to ensure we only get a match for the exact name
    STATUS=$(docker inspect -f '{{.State.Running}}' "$container_name" 2>/dev/null)

    if [ "$STATUS" == "true" ]; then
        return 0
    else
        return 1
    fi
}

# 1. Check Primary Service
if ! check_container "$SERVICE_LIST"; then
    echo "CRITICAL: Service $SERVICE_LIST is down."
    exit 1
fi

# 2. Check Dependency (if provided)
if [ -n "$DEPENDENCY" ]; then
    if ! check_container "$DEPENDENCY"; then
        echo "CRITICAL: Dependency $DEPENDENCY is down."
        exit 1
    fi
fi

# 3. Everything is healthy
exit 0