#!/bin/bash
# Test script for logcorrelator RPM package
# Verifies installation, permissions, and service status
#
# Usage: ./packaging/test/test-rpm.sh [el8|el9|el10]
#
# This script tests the RPM package in a Docker container to ensure:
# - Installation succeeds
# - File permissions are correct
# - Service starts properly
# - Sockets are created with correct ownership

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$(dirname "$SCRIPT_DIR")")"
RPM_DIR="${PROJECT_ROOT}/dist/rpm"

# Default to el8 if no argument provided
DISTRO="${1:-el8}"

echo "========================================="
echo "Testing logcorrelator RPM for ${DISTRO}"
echo "========================================="

# Find the RPM file
case "${DISTRO}" in
    el8|rocky8)
        RPM_PATH="${RPM_DIR}/el8"
        BASE_IMAGE="rockylinux:8"
        ;;
    el9|rocky9)
        RPM_PATH="${RPM_DIR}/el9"
        BASE_IMAGE="rockylinux:9"
        ;;
    el10|alma10)
        RPM_PATH="${RPM_DIR}/el10"
        BASE_IMAGE="almalinux:10"
        ;;
    *)
        echo "Unknown distribution: ${DISTRO}"
        echo "Valid options: el8, el9, el10"
        exit 1
        ;;
esac

# Find the latest RPM file — build it first if missing
RPM_FILE=$(ls -t "${RPM_PATH}"/logcorrelator-*.rpm 2>/dev/null | head -n 1)

if [ -z "${RPM_FILE}" ]; then
    echo "No RPM found in ${RPM_PATH} — building now via Dockerfile.package..."
    REPO_ROOT="$(dirname "$(dirname "$(dirname "$SCRIPT_DIR")")")"
    VERSION="${VERSION:-$(git -C "${REPO_ROOT}" describe --tags --abbrev=0 2>/dev/null | sed 's/^v//' || echo "0.0.0-dev")}"
    docker build \
        --build-arg VERSION="${VERSION}" \
        -f "${REPO_ROOT}/services/correlator/Dockerfile.package" \
        --target output \
        -o "${RPM_DIR}" \
        "${REPO_ROOT}"
    RPM_FILE=$(ls -t "${RPM_PATH}"/logcorrelator-*.rpm 2>/dev/null | head -n 1)
fi

if [ -z "${RPM_FILE}" ]; then
    echo "ERROR: RPM build failed — no RPM found in ${RPM_PATH}"
    exit 1
fi

echo "Testing RPM: ${RPM_FILE}"
echo "Base image: ${BASE_IMAGE}"
echo ""

# Create test script
TEST_SCRIPT=$(cat <<'EOF'
#!/bin/bash
set -e

echo "=== Installing logcorrelator RPM ==="
rpm -ivh /tmp/logcorrelator.rpm

echo ""
echo "=== Checking user and group ==="
if ! getent group logcorrelator >/dev/null; then
    echo "FAIL: logcorrelator group not created"
    exit 1
fi
echo "OK: logcorrelator group exists"

if ! getent passwd logcorrelator >/dev/null; then
    echo "FAIL: logcorrelator user not created"
    exit 1
fi
echo "OK: logcorrelator user exists"

echo ""
echo "=== Checking directory permissions ==="

# Check /var/run/logcorrelator
DIR="/var/run/logcorrelator"
if [ ! -d "$DIR" ]; then
    echo "FAIL: $DIR does not exist"
    exit 1
fi
OWNER=$(stat -c '%U:%G' "$DIR")
PERMS=$(stat -c '%a' "$DIR")
if [ "$OWNER" != "logcorrelator:logcorrelator" ]; then
    echo "FAIL: $DIR owner is $OWNER (expected logcorrelator:logcorrelator)"
    exit 1
fi
if [ "$PERMS" != "755" ]; then
    echo "FAIL: $DIR permissions are $PERMS (expected 755)"
    exit 1
fi
echo "OK: $DIR - owner=$OWNER, permissions=$PERMS"

# Check /var/log/logcorrelator
DIR="/var/log/logcorrelator"
if [ ! -d "$DIR" ]; then
    echo "FAIL: $DIR does not exist"
    exit 1
fi
OWNER=$(stat -c '%U:%G' "$DIR")
PERMS=$(stat -c '%a' "$DIR")
if [ "$OWNER" != "logcorrelator:logcorrelator" ]; then
    echo "FAIL: $DIR owner is $OWNER (expected logcorrelator:logcorrelator)"
    exit 1
fi
if [ "$PERMS" != "750" ]; then
    echo "FAIL: $DIR permissions are $PERMS (expected 750)"
    exit 1
fi
echo "OK: $DIR - owner=$OWNER, permissions=$PERMS"

# Check /var/lib/logcorrelator
DIR="/var/lib/logcorrelator"
if [ ! -d "$DIR" ]; then
    echo "FAIL: $DIR does not exist"
    exit 1
fi
OWNER=$(stat -c '%U:%G' "$DIR")
PERMS=$(stat -c '%a' "$DIR")
if [ "$OWNER" != "logcorrelator:logcorrelator" ]; then
    echo "FAIL: $DIR owner is $OWNER (expected logcorrelator:logcorrelator)"
    exit 1
fi
if [ "$PERMS" != "750" ]; then
    echo "FAIL: $DIR permissions are $PERMS (expected 750)"
    exit 1
fi
echo "OK: $DIR - owner=$OWNER, permissions=$PERMS"

echo ""
echo "=== Checking config files ==="

# Check config file exists and has correct permissions
CONFIG="/etc/logcorrelator/logcorrelator.yml"
if [ ! -f "$CONFIG" ]; then
    echo "FAIL: $CONFIG does not exist"
    exit 1
fi
OWNER=$(stat -c '%U:%G' "$CONFIG")
PERMS=$(stat -c '%a' "$CONFIG")
if [ "$OWNER" != "logcorrelator:logcorrelator" ]; then
    echo "FAIL: $CONFIG owner is $OWNER (expected logcorrelator:logcorrelator)"
    exit 1
fi
if [ "$PERMS" != "640" ]; then
    echo "FAIL: $CONFIG permissions are $PERMS (expected 640)"
    exit 1
fi
echo "OK: $CONFIG - owner=$OWNER, permissions=$PERMS"

# Check example config file
EXAMPLE_CONFIG="/etc/logcorrelator/logcorrelator.yml.example"
if [ ! -f "$EXAMPLE_CONFIG" ]; then
    echo "FAIL: $EXAMPLE_CONFIG does not exist"
    exit 1
fi
OWNER=$(stat -c '%U:%G' "$EXAMPLE_CONFIG")
PERMS=$(stat -c '%a' "$EXAMPLE_CONFIG")
if [ "$OWNER" != "logcorrelator:logcorrelator" ]; then
    echo "FAIL: $EXAMPLE_CONFIG owner is $OWNER (expected logcorrelator:logcorrelator)"
    exit 1
fi
if [ "$PERMS" != "640" ]; then
    echo "FAIL: $EXAMPLE_CONFIG permissions are $PERMS (expected 640)"
    exit 1
fi
echo "OK: $EXAMPLE_CONFIG - owner=$OWNER, permissions=$PERMS"

echo ""
echo "=== Checking systemd service ==="
# Packaged units must be in /usr/lib/systemd/system, not /etc/systemd/system
if [ ! -f /usr/lib/systemd/system/logcorrelator.service ]; then
    echo "FAIL: systemd service file not found at /usr/lib/systemd/system/logcorrelator.service"
    exit 1
fi
echo "OK: systemd service file exists at /usr/lib/systemd/system/"

echo ""
echo "=== Checking logrotate config ==="
if [ ! -f /etc/logrotate.d/logcorrelator ]; then
    echo "FAIL: logrotate config not found"
    exit 1
fi
echo "OK: logrotate config exists"

echo ""
echo "=== Testing service start ==="
# Try to start the service (may fail in container without full systemd)
if command -v systemctl >/dev/null 2>&1; then
    systemctl daemon-reload || true
    if systemctl start logcorrelator.service 2>/dev/null; then
        echo "OK: service started successfully"
        
        # Wait for sockets to be created
        sleep 2
        
        echo ""
        echo "=== Checking sockets ==="
        HTTP_SOCKET="/var/run/logcorrelator/http.socket"
        NETWORK_SOCKET="/var/run/logcorrelator/network.socket"
        
        if [ -S "$HTTP_SOCKET" ]; then
            OWNER=$(stat -c '%U:%G' "$HTTP_SOCKET")
            PERMS=$(stat -c '%a' "$HTTP_SOCKET")
            echo "OK: $HTTP_SOCKET exists - owner=$OWNER, permissions=$PERMS"
            if [ "$PERMS" != "666" ]; then
                echo "WARN: socket permissions are $PERMS (expected 666)"
            fi
        else
            echo "WARN: $HTTP_SOCKET not found (service may not have started)"
        fi
        
        if [ -S "$NETWORK_SOCKET" ]; then
            OWNER=$(stat -c '%U:%G' "$NETWORK_SOCKET")
            PERMS=$(stat -c '%a' "$NETWORK_SOCKET")
            echo "OK: $NETWORK_SOCKET exists - owner=$OWNER, permissions=$PERMS"
            if [ "$PERMS" != "666" ]; then
                echo "WARN: socket permissions are $PERMS (expected 666)"
            fi
        else
            echo "WARN: $NETWORK_SOCKET not found (service may not have started)"
        fi
        
        systemctl stop logcorrelator.service || true
    else
        echo "WARN: service failed to start (expected in minimal container)"
    fi
else
    echo "WARN: systemctl not available (minimal container)"
fi

echo ""
echo "========================================="
echo "All tests passed!"
echo "========================================="
EOF
)

# Run test in Docker container
echo "Running tests in Docker container..."
echo ""

docker run --rm \
    -v "${RPM_FILE}:/tmp/logcorrelator.rpm:ro" \
    -v "${TEST_SCRIPT}:/test.sh:ro" \
    "${BASE_IMAGE}" \
    bash /test.sh

echo ""
echo "Test completed successfully for ${DISTRO}"
