#!/bin/bash
################################################################################
# Script Name: lynis-metrics-exporter.sh
# Version: 1.01
# Description: Prometheus exporter for Lynis security auditing — hardening
#              index, test pass/fail/skip counts, warnings, suggestions,
#              component scores, and scan metadata
#
# Author: Phil Connor
# Contact: contact@mylinux.work
# Website: https://mylinux.work
# License: MIT
#
# Prerequisites:
#   - Lynis installed (lynis command available)
#   - Root/sudo access (Lynis requires root for full audit)
#   - awk, grep
#
# Usage:
#   # Output to stdout
#   sudo ./lynis-metrics-exporter.sh
#
#   # Textfile collector mode
#   sudo ./lynis-metrics-exporter.sh --textfile
#
#   # HTTP server mode
#   sudo ./lynis-metrics-exporter.sh --http -p 9194
#
# Metrics Exported:
#   - lynis_up - Exporter status (1=up, 0=down)
#   - lynis_exporter_info{version} - Exporter version info
#   - lynis_hardening_index - Overall hardening score (0-100)
#   - lynis_tests_performed - Total tests run
#   - lynis_tests_passed - Tests passed
#   - lynis_tests_failed - Tests failed
#   - lynis_tests_skipped - Tests skipped
#   - lynis_warnings_total - Total warnings
#   - lynis_suggestions_total - Total suggestions
#   - lynis_plugins_enabled - Enabled plugins count
#   - lynis_vulnerable_packages - Packages with known vulnerabilities
#   - lynis_firewall_active - Firewall detected and active (1/0)
#   - lynis_malware_scanner - Malware scanner present (1/0)
#   - lynis_scan_duration_seconds - Lynis audit duration
#   - lynis_exporter_duration_seconds - Script execution time
#   - lynis_exporter_last_run_timestamp - Last run timestamp
#
# Configuration:
#   Default HTTP port: 9194
#   Textfile directory: /var/lib/node_exporter
#   Lynis report: /var/log/lynis-report.dat
#
################################################################################

# ============================================================================
# CONFIGURATION VARIABLES
# ============================================================================

TEXTFILE_DIR="/var/lib/node_exporter"
OUTPUT_FILE=""
HTTP_MODE=false
HTTP_PORT=9194
LYNIS_REPORT="/var/log/lynis-report.dat"
RUN_AUDIT=false
EXPORTER_VERSION="1.0"

# ============================================================================
# HELPER FUNCTIONS
# ============================================================================

show_usage() {
    cat <<EOF
Usage: $0 [OPTIONS]

Export Lynis security audit results as Prometheus metrics.

MODES:
    --textfile      Write to node_exporter textfile collector
    --http          Run HTTP server on port $HTTP_PORT

OPTIONS:
    -p, --port        HTTP port (default: $HTTP_PORT)
    -o, --output      Output file path
    --report PATH     Path to lynis-report.dat (default: $LYNIS_REPORT)
    --run-audit       Run lynis audit before exporting (slow, use with cron)

EXAMPLES:
    sudo $0 --textfile
    sudo $0 --textfile --run-audit
    sudo $0 --http --port 9194
    sudo $0 --report /var/log/lynis-report.dat

EOF
    exit 0
}

parse_args() {
    while [[ $# -gt 0 ]]; do
        case $1 in
            -h|--help) show_usage ;;
            --textfile) OUTPUT_FILE="$TEXTFILE_DIR/lynis.prom"; shift ;;
            --http) HTTP_MODE=true; shift ;;
            -p|--port) HTTP_PORT="$2"; shift 2 ;;
            -o|--output) OUTPUT_FILE="$2"; shift 2 ;;
            --report) LYNIS_REPORT="$2"; shift 2 ;;
            --run-audit) RUN_AUDIT=true; shift ;;
            *) echo "Unknown option: $1" >&2; exit 1 ;;
        esac
    done
}

prom_escape() {
    local val="$1"
    val="${val//\\/\\\\}"
    val="${val//\"/\\\"}"
    val="${val//$'\n'/}"
    echo "$val"
}

get_report_value() {
    local key="$1"
    grep "^${key}=" "$LYNIS_REPORT" 2>/dev/null | head -1 | cut -d'=' -f2-
}

count_report_key() {
    local key="$1"
    grep -c "^${key}" "$LYNIS_REPORT" 2>/dev/null || true
}

# ============================================================================
# METRIC GENERATION
# ============================================================================

generate_metrics() {
    local script_start
    script_start=$(date +%s)

    # Run audit if requested
    if [ "$RUN_AUDIT" = true ]; then
        lynis audit system --quick --no-colors --quiet 2>/dev/null
    fi

    # Check if report exists
    if [ ! -f "$LYNIS_REPORT" ]; then
        cat <<EOF
# HELP lynis_up Lynis exporter status
# TYPE lynis_up gauge
lynis_up 0
EOF
        return
    fi

    cat <<EOF
# HELP lynis_up Lynis exporter status
# TYPE lynis_up gauge
lynis_up 1

# HELP lynis_exporter_info Exporter version information
# TYPE lynis_exporter_info gauge
lynis_exporter_info{version="$EXPORTER_VERSION"} 1
EOF

    echo ""

    # ========================================================================
    # HARDENING INDEX
    # ========================================================================

    local hardening_index
    hardening_index=$(get_report_value "hardening_index")
    hardening_index=${hardening_index:-0}

    cat <<EOF
# HELP lynis_hardening_index Overall hardening score (0-100)
# TYPE lynis_hardening_index gauge
lynis_hardening_index $hardening_index
EOF

    echo ""

    # ========================================================================
    # TEST RESULTS
    # ========================================================================

    local tests_performed tests_skipped
    tests_performed=$(get_report_value "tests_performed")
    tests_performed=${tests_performed:-0}

    local warnings suggestions
    warnings=$(count_report_key "warning\[\]")
    suggestions=$(count_report_key "suggestion\[\]")

    # Count pass/fail from report
    local tests_category_count
    tests_category_count=$(grep -c "^test_result=" "$LYNIS_REPORT" 2>/dev/null || true)

    local tests_passed tests_failed
    tests_passed=$(grep "^test_result=OK" "$LYNIS_REPORT" 2>/dev/null | wc -l)
    tests_failed=$(grep "^test_result=WARNING\|^test_result=SUGGESTION\|^test_result=DIFFERENT\|^test_result=WEAK" "$LYNIS_REPORT" 2>/dev/null | wc -l)
    local tests_skipped_count
    tests_skipped_count=$(grep -c "^test_skipped=" "$LYNIS_REPORT" 2>/dev/null || true)

    cat <<EOF
# HELP lynis_tests_performed Total tests performed
# TYPE lynis_tests_performed gauge
lynis_tests_performed $tests_performed

# HELP lynis_tests_passed Tests passed
# TYPE lynis_tests_passed gauge
lynis_tests_passed $tests_passed

# HELP lynis_tests_failed Tests failed or with findings
# TYPE lynis_tests_failed gauge
lynis_tests_failed $tests_failed

# HELP lynis_tests_skipped Tests skipped
# TYPE lynis_tests_skipped gauge
lynis_tests_skipped $tests_skipped_count

# HELP lynis_warnings_total Total warnings
# TYPE lynis_warnings_total gauge
lynis_warnings_total $warnings

# HELP lynis_suggestions_total Total suggestions
# TYPE lynis_suggestions_total gauge
lynis_suggestions_total $suggestions
EOF

    echo ""

    # ========================================================================
    # SECURITY CHECKS
    # ========================================================================

    local firewall_active=0
    local malware_scanner=0
    local vulnerable_packages=0

    if get_report_value "firewall_active" | grep -qi "1\|yes\|true" 2>/dev/null; then
        firewall_active=1
    fi

    if get_report_value "malware_scanner_installed" | grep -qi "1\|yes\|true" 2>/dev/null; then
        malware_scanner=1
    fi

    vulnerable_packages=$(get_report_value "vulnerable_packages_found")
    vulnerable_packages=${vulnerable_packages:-0}

    local plugins_enabled
    plugins_enabled=$(get_report_value "plugins_enabled")
    plugins_enabled=${plugins_enabled:-0}

    cat <<EOF
# HELP lynis_firewall_active Firewall detected and active
# TYPE lynis_firewall_active gauge
lynis_firewall_active $firewall_active

# HELP lynis_malware_scanner Malware scanner installed
# TYPE lynis_malware_scanner gauge
lynis_malware_scanner $malware_scanner

# HELP lynis_vulnerable_packages Packages with known vulnerabilities
# TYPE lynis_vulnerable_packages gauge
lynis_vulnerable_packages $vulnerable_packages

# HELP lynis_plugins_enabled Enabled Lynis plugins
# TYPE lynis_plugins_enabled gauge
lynis_plugins_enabled $plugins_enabled
EOF

    echo ""

    # ========================================================================
    # SCAN METADATA
    # ========================================================================

    local lynis_version
    lynis_version=$(get_report_value "lynis_version")

    if [ -n "$lynis_version" ]; then
        cat <<EOF
# HELP lynis_version_info Lynis version information
# TYPE lynis_version_info gauge
lynis_version_info{version="$lynis_version"} 1
EOF
        echo ""
    fi

    # ========================================================================
    # EXPORTER RUNTIME
    # ========================================================================

    local script_end script_duration
    script_end=$(date +%s)
    script_duration=$((script_end - script_start))

    cat <<EOF
# HELP lynis_exporter_duration_seconds Time to generate all metrics
# TYPE lynis_exporter_duration_seconds gauge
lynis_exporter_duration_seconds $script_duration

# HELP lynis_exporter_last_run_timestamp Unix timestamp of last successful run
# TYPE lynis_exporter_last_run_timestamp gauge
lynis_exporter_last_run_timestamp $script_end
EOF
}

# ============================================================================
# HTTP SERVER MODE
# ============================================================================

run_http_server() {
    echo "Starting Lynis exporter on port $HTTP_PORT..." >&2

    if ! command -v nc >/dev/null 2>&1; then
        echo "ERROR: netcat (nc) required for HTTP mode" >&2
        exit 1
    fi

    while true; do
        {
            read -r request
            if [[ "$request" =~ ^GET\ /metrics ]]; then
                echo -e "HTTP/1.1 200 OK\r\nContent-Type: text/plain; version=0.0.4\r\n\r"
                generate_metrics
            else
                echo -e "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r"
                cat <<EOF
<!DOCTYPE html>
<html>
<head><title>Lynis Exporter v$EXPORTER_VERSION</title></head>
<body>
<h1>Lynis Prometheus Exporter v$EXPORTER_VERSION</h1>
<p><a href="/metrics">Metrics</a></p>
</body>
</html>
EOF
            fi
        } | nc -l -p "$HTTP_PORT" -q 1 2>/dev/null
    done
}

# ============================================================================
# MAIN EXECUTION
# ============================================================================

main() {
    parse_args "$@"

    if [ "$HTTP_MODE" = true ]; then
        run_http_server
    elif [ -n "$OUTPUT_FILE" ]; then
        local output_dir
        output_dir="$(dirname "$OUTPUT_FILE")"
        mkdir -p "$output_dir"

        local temp_file
        temp_file=$(mktemp "${output_dir}/.lynis_metrics.XXXXXX")

        if ! generate_metrics > "$temp_file" 2>/dev/null; then
            rm -f "$temp_file"
            echo "ERROR: Failed to generate metrics" >&2
            exit 1
        fi

        local file_lines
        file_lines=$(wc -l < "$temp_file" 2>/dev/null || echo 0)

        if [ "$file_lines" -lt 5 ]; then
            rm -f "$temp_file"
            echo "ERROR: Metrics file too small ($file_lines lines)" >&2
            exit 1
        fi

        chmod 644 "$temp_file"
        mv -f "$temp_file" "$OUTPUT_FILE"
        echo "Metrics written to $OUTPUT_FILE ($file_lines lines)" >&2
    else
        generate_metrics
    fi
}

main "$@"
