#!/bin/bash

# USM Agent configuration validator using /dev/tcp
# Usage: usm-agent-validz <port> <path>
# Returns 0 on HTTP 200, non-zero on any other status or connection failure

usm-agent-validz() {

    # Set hostname, port, and path
    local hostname="localhost"
    local port=${1:-9999}
    local path=${2:-"/validz"}

    # Validate port is numeric
    if ! [[ "$port" =~ ^[0-9]+$ ]]; then
        echo "Error: Invalid port number '$port'" >&2
        return 1
    fi

    # Validate port is within valid range (1-65535)
    if [ "$port" -lt 1 ] || [ "$port" -gt 65535 ]; then
        echo "Error: Port number '$port' out of range (1-65535)" >&2
        return 1
    fi

    # Create temporary file for response
    local temp_file=$(mktemp)
    trap "rm -f '$temp_file'" EXIT

    echo "Checking $hostname:$port$path"

    # Make HTTP request with timeout using background process
    {
        {
            exec 3<>"/dev/tcp/$hostname/$port" 2>/dev/null && \
            printf "GET %s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n" "$path" "$hostname" >&3 && \
            head -1 <&3 > "$temp_file" && \
            exec 3<&- 3>&-
        } &
        local pid=$!

        # Wait for up to 10 seconds
        local count=0
        while [[ $count -lt 100 ]] && kill -0 "$pid" 2>/dev/null; do
            sleep 0.1
            ((count++))
        done

        # Kill the process if it's still running
        if kill -0 "$pid" 2>/dev/null; then
            kill -9 "$pid" 2>/dev/null
            wait "$pid" 2>/dev/null
            echo "Error: Request timeout after 10 seconds" >&2
            return 1
        fi

        wait "$pid"
    } 2>/dev/null || {
        echo "Error: Cannot connect to $hostname:$port" >&2
        return 1
    }

    # Read status line from temp file
    local status_line=""
    if [[ -f "$temp_file" ]]; then
        status_line=$(cat "$temp_file")
    fi

    # Check if we got a response
    if [[ -z "$status_line" ]]; then
        echo "Error: No response received" >&2
        return 1
    fi

    # Remove carriage return from status line
    status_line="${status_line%$'\r'}"

    # Extract status code from status line
    local status_code=""
    local status_message=""
    if [[ "$status_line" =~ ^HTTP/[0-9.]+[[:space:]]+([0-9]+)(.*)$ ]]; then
        status_code="${BASH_REMATCH[1]}"
        status_message="${BASH_REMATCH[2]# }"
    fi

    # Check if we got a valid HTTP response
    if [[ -z "$status_code" ]]; then
        echo "Error: Invalid HTTP response received: '$status_line'" >&2
        return 1
    fi

    # Handle response based on status code
    if [[ "$status_code" == "200" ]]; then
        # 200 status - print status to stdout and return zero
        echo "HTTP $status_code $status_message"
        return 0
    else
        # Non-200 status - print status to stderr and return non-zero
        echo "HTTP $status_code $status_message" >&2
        return 1
    fi
}

usm-agent-validz "$@"