#!/bin/bash
set -euo pipefail

# -------- Configuration --------
APPRISE_URL="tgram://5862752875:AAHo7tPSIhUIAtGhHLqRmsokpPMQ__K4clU/-1001730456573"
DEFAULT_EXCLUDED_CONTAINERS=("monitoring-agent" "immich_db" "traefik")
EXCLUDED_CONTAINERS=("${DEFAULT_EXCLUDED_CONTAINERS[@]}")
EXCLUDED_HOSTS=()

hostname=$(hostname)
use_apprise=false

# -------- Apprise Availability Check --------
if command -v apprise &>/dev/null && [ -n "$APPRISE_URL" ]; then
    use_apprise=true
fi

# -------- Load List from File Helper --------
load_list_from_file() {
    local file="$1"
    while IFS= read -r line; do
        [[ -n "$line" && ! "$line" =~ ^# ]] && echo "$line"
    done < "$file"
}

# -------- Argument Parsing --------
while [[ $# -gt 0 ]]; do
    case "$1" in
        --exclude-container)
            EXCLUDED_CONTAINERS+=("$2")
            shift 2
            ;;
        --exclude-container-file)
            if [[ -f "$2" ]]; then
                mapfile -t new_containers < <(load_list_from_file "$2")
                EXCLUDED_CONTAINERS+=("${new_containers[@]}")
            else
                echo "❌ Container exclusion file not found: $2"
                exit 1
            fi
            shift 2
            ;;
        --exclude-host)
            EXCLUDED_HOSTS+=("$2")
            shift 2
            ;;
        --exclude-host-file)
            if [[ -f "$2" ]]; then
                mapfile -t new_hosts < <(load_list_from_file "$2")
                EXCLUDED_HOSTS+=("${new_hosts[@]}")
            else
                echo "❌ Host exclusion file not found: $2"
                exit 1
            fi
            shift 2
            ;;
        --apprise-url)
            APPRISE_URL="$2"
            shift 2
            ;;
        --help|-h)
            echo "Usage: $0 [--exclude-host HOST] [--exclude-container NAME] [--exclude-host-file FILE] [--exclude-container-file FILE] [--apprise-url URL]"
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            exit 1
            ;;
    esac
done

# -------- Host Exclusion Check --------
for h in "${EXCLUDED_HOSTS[@]}"; do
    if [[ "$hostname" == "$h" ]]; then
        echo "ℹ️ Host '$hostname' is excluded from health checks."
        exit 0
    fi
done

# -------- Docker Check --------
if ! command -v docker &>/dev/null; then
    echo "❌ Docker is not installed or not in PATH."
    exit 1
fi

# -------- Main Logic --------
message="🚨 Docker Container Health Check on '$hostname'\n\n"
issues_found=false
containers=$(docker ps -q)

if [ -z "$containers" ]; then
    message+="No running containers found.\n"
    issues_found=true
else
    for container in $containers; do
        name=$(docker inspect --format='{{.Name}}' "$container" | sed 's/^\/\+//')

        for excluded in "${EXCLUDED_CONTAINERS[@]}"; do
            if [[ "$name" == *"$excluded"* ]]; then
                continue 2
            fi
        done

        health_status=$(docker inspect --format='{{.State.Health.Status}}' "$container" 2>/dev/null || echo "none")

        if [[ "$health_status" == "none" ]]; then
            message+="ℹ️  Container '$name' has no health check defined.\n"
            issues_found=true
        elif [[ "$health_status" != "healthy" ]]; then
            message+="⚠️  Container '$name' is in state: $health_status\n"
            issues_found=true
        fi
    done
fi

# -------- Notify --------
if $issues_found; then
    if $use_apprise; then
        apprise -t "Docker Health Alert - $hostname" -b "$(echo -e "$message")" "$APPRISE_URL"
    else
        echo -e "$message"
    fi
else
    echo "✅ [$hostname] All relevant containers are healthy and have defined health checks."
fi