#!/bin/bash
################################################################################
# Script Name: dokku-exporter.sh
# Version: 1.0
# Description: Prometheus exporter for Dokku PaaS providing operational
#              metrics via the Dokku CLI — application status, plugin counts,
#              domain configuration, SSL status, and host health
#
# Author: Phil Connor
# Contact: contact@mylinux.work
# Website: https://mylinux.work
# License: MIT
#
# Prerequisites:
#   - Dokku installed on the local host
#   - Root or dokku user access to run dokku commands
#   - netcat (nc) for HTTP mode
#
# Usage:
#   # Output to stdout
#   ./dokku-exporter.sh
#
#   # HTTP server mode
#   ./dokku-exporter.sh --http -p 9198
#
#   # Textfile collector mode
#   ./dokku-exporter.sh --textfile
#
# Metrics Exported:
#   - dokku_up - Dokku reachability (1=up, 0=down)
#   - dokku_info{version} - Dokku version info
#   - dokku_apps_total - Total app count
#   - dokku_apps_running - Running apps
#   - dokku_apps_stopped - Stopped apps
#   - dokku_plugins_total - Installed plugin count
#   - dokku_domains_app_total - Total app domains configured
#   - dokku_ssl_enabled_total - Apps with SSL enabled
#   - dokku_exporter_duration_seconds - Script execution time
#   - dokku_exporter_last_run_timestamp - Last run timestamp
#
# Configuration:
#   Default HTTP port: 9198
#   Textfile directory: /var/lib/node_exporter
#
################################################################################

set -euo pipefail

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

TEXTFILE_DIR="/var/lib/node_exporter"
OUTPUT_FILE=""
HTTP_MODE=false
HTTP_PORT=9198

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

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

Export Dokku PaaS statistics as Prometheus metrics via the Dokku CLI.

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

OPTIONS:
    -p, --port        HTTP port (default: 9198)
    -o, --output      Output file path

EXAMPLES:
    $0 --textfile                    # Write to textfile collector
    $0 --http --port 9198            # Run HTTP server
    $0                               # Output to stdout
    $0 -o /tmp/dokku.prom            # Write to custom file

EOF
    exit 0
}

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

# Check prerequisites
# Returns: 0 if OK, 1 if error
check_prerequisites() {
    if ! command -v dokku >/dev/null 2>&1; then
        echo "ERROR: dokku not found" >&2
        return 1
    fi

    return 0
}

# Escape special characters in Prometheus label values
# Args: $1 - string to escape
# Returns: escaped string safe for Prometheus labels
prom_escape() {
    local val="$1"
    val="${val//\\/\\\\}"
    val="${val//\"/\\\"}"
    val="${val//$'\n'/}"
    echo "$val"
}

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

# Generate all Prometheus metrics
# Returns: Prometheus text format metrics on stdout
generate_metrics() {
    local script_start
    script_start=$(date +%s)

    # Check prerequisites
    if ! check_prerequisites; then
        cat <<EOF
# HELP dokku_up Dokku reachability (1=up, 0=down)
# TYPE dokku_up gauge
dokku_up 0
EOF
        return
    fi

    # Verify Dokku is responding
    local version_output
    version_output=$(dokku version 2>/dev/null)

    if [ -z "$version_output" ]; then
        cat <<EOF
# HELP dokku_up Dokku reachability (1=up, 0=down)
# TYPE dokku_up gauge
dokku_up 0
EOF
        return
    fi

    # Extract version string (e.g., "dokku version 0.38.0" -> "0.38.0")
    local dokku_version
    dokku_version=$(echo "$version_output" | awk '{print $NF}')

    if [ -z "$dokku_version" ]; then
        cat <<EOF
# HELP dokku_up Dokku reachability (1=up, 0=down)
# TYPE dokku_up gauge
dokku_up 0
EOF
        return
    fi

    cat <<EOF
# HELP dokku_up Dokku reachability (1=up, 0=down)
# TYPE dokku_up gauge
dokku_up 1
EOF

    echo ""

    # ========================================================================
    # VERSION INFO
    # ========================================================================

    cat <<EOF
# HELP dokku_info Dokku version information
# TYPE dokku_info gauge
dokku_info{version="$(prom_escape "$dokku_version")"} 1
EOF

    echo ""

    # ========================================================================
    # APPLICATION METRICS
    # ========================================================================

    local apps_list
    apps_list=$(dokku --quiet apps:list 2>/dev/null || true)

    local total_apps=0
    local running_apps=0
    local stopped_apps=0

    if [ -n "$apps_list" ]; then
        total_apps=$(echo "$apps_list" | wc -l)
        total_apps=${total_apps:-0}

        # Count running apps by checking each app's process status
        while IFS= read -r app; do
            local ps_running
            ps_running=$(dokku ps:report "$app" --ps-running 2>/dev/null || echo "false")
            if [ "$ps_running" = "true" ]; then
                running_apps=$((running_apps + 1))
            fi
        done <<< "$apps_list"

        stopped_apps=$((total_apps - running_apps))
    fi

    cat <<EOF
# HELP dokku_apps_total Total number of apps
# TYPE dokku_apps_total gauge
dokku_apps_total $total_apps

# HELP dokku_apps_running Running apps
# TYPE dokku_apps_running gauge
dokku_apps_running $running_apps

# HELP dokku_apps_stopped Stopped apps
# TYPE dokku_apps_stopped gauge
dokku_apps_stopped $stopped_apps
EOF

    echo ""

    # ========================================================================
    # PLUGIN METRICS
    # ========================================================================

    local plugins_count=0
    plugins_count=$(dokku plugin:list 2>/dev/null | wc -l)
    plugins_count=${plugins_count:-0}

    cat <<EOF
# HELP dokku_plugins_total Installed plugins
# TYPE dokku_plugins_total gauge
dokku_plugins_total $plugins_count
EOF

    echo ""

    # ========================================================================
    # DOMAIN METRICS
    # ========================================================================

    local total_domains=0

    if [ -n "$apps_list" ]; then
        while IFS= read -r app; do
            local app_domains
            app_domains=$(dokku domains:report "$app" --domains-app-vhosts 2>/dev/null || true)
            if [ -n "$app_domains" ]; then
                # Domains are space-separated; count words
                local domain_count
                domain_count=$(echo "$app_domains" | wc -w)
                total_domains=$((total_domains + domain_count))
            fi
        done <<< "$apps_list"
    fi

    cat <<EOF
# HELP dokku_domains_app_total Total app domains configured
# TYPE dokku_domains_app_total gauge
dokku_domains_app_total $total_domains
EOF

    echo ""

    # ========================================================================
    # SSL METRICS
    # ========================================================================

    local ssl_enabled_count=0

    if [ -n "$apps_list" ]; then
        while IFS= read -r app; do
            local ssl_enabled
            ssl_enabled=$(dokku certs:report "$app" --certs-ssl-enabled 2>/dev/null || echo "false")
            if [ "$ssl_enabled" = "true" ]; then
                ssl_enabled_count=$((ssl_enabled_count + 1))
            fi
        done <<< "$apps_list"
    fi

    cat <<EOF
# HELP dokku_ssl_enabled_total Apps with SSL enabled
# TYPE dokku_ssl_enabled_total gauge
dokku_ssl_enabled_total $ssl_enabled_count
EOF

    echo ""

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

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

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

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

    echo ""
}

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

# Run simple HTTP server using netcat
# Serves metrics on /metrics endpoint
run_http_server() {
    echo "Starting Dokku 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

    # Infinite loop accepting HTTP requests
    while true; do
        {
            read -r request
            # Check if request is for /metrics endpoint
            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  # Serve HTML landing page for other requests
                echo -e "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r"
                cat <<EOF
<!DOCTYPE html>
<html>
<head><title>Dokku Exporter v1.0</title></head>
<body>
<h1>Dokku Prometheus Exporter v1.0</h1>
<p><a href="/metrics">Metrics</a></p>
<p>Operational metrics from the Dokku CLI.</p>
</body>
</html>
EOF
            fi
        } | nc -l -p "$HTTP_PORT" -q 1 2>/dev/null
    done
}

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

# Main entry point - routes to appropriate output mode
main() {
    parse_args "$@"

    if [ "$HTTP_MODE" = true ]; then
        # Run HTTP server (blocks until killed)
        run_http_server
    elif [ -n "$OUTPUT_FILE" ]; then
        # Textfile collector mode: write atomically using temp file
        local output_dir
        output_dir="$(dirname "$OUTPUT_FILE")"
        mkdir -p "$output_dir"

        # Create temp file in SAME directory for atomic rename (same filesystem)
        local temp_file
        temp_file=$(mktemp "${output_dir}/.dokku_metrics.XXXXXX")

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

        # Validate: file must exist, have content
        local file_lines
        file_lines=$(wc -l < "$temp_file" 2>/dev/null || echo 0)

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

        # Set permissions before move
        chmod 644 "$temp_file"

        # Atomic rename - no gap where file is missing
        mv -f "$temp_file" "$OUTPUT_FILE"

        echo "Metrics written to $OUTPUT_FILE ($file_lines lines)" >&2
    else
        # Default: output to stdout
        generate_metrics
    fi
}

# Execute main function with all script arguments
main "$@"
