#!/bin/bash
# ============================================================================================================
# Script: fail2ban-manager.sh
# Description: Manage Fail2Ban configuration based on database settings
# Author: SoftSwitch Team
# Date: 2025-12-06
# ============================================================================================================

set -euo pipefail

# Configuration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
FAIL2BAN_DIR="/etc/fail2ban"
JAIL_LOCAL="${FAIL2BAN_DIR}/jail.local"
JAIL_D_DIR="${FAIL2BAN_DIR}/jail.d"
ODBC_INI="/etc/odbc.ini"

# Pure-bash whitespace trimmer (avoids unsafe `echo "$val" | xargs` quote/backslash mangling)
trim_ws() {
    local s="${1:-}"
    s="${s#"${s%%[![:space:]]*}"}"
    s="${s%"${s##*[![:space:]]}"}"
    printf '%s' "$s"
}

# Strict IPv4 / IPv6 / CIDR validation before any nft execution
validate_ip_or_cidr() {
    local ip="${1:-}"
    [ -z "$ip" ] && return 1
    if [[ "$ip" =~ ^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})(/([0-9]{1,2}))?$ ]]; then
        local o1="${BASH_REMATCH[1]}" o2="${BASH_REMATCH[2]}" o3="${BASH_REMATCH[3]}" o4="${BASH_REMATCH[4]}" prefix="${BASH_REMATCH[6]:-}"
        if [ "$o1" -gt 255 ] || [ "$o2" -gt 255 ] || [ "$o3" -gt 255 ] || [ "$o4" -gt 255 ]; then
            return 1
        fi
        if [ -n "$prefix" ] && [ "$prefix" -gt 32 ]; then
            return 1
        fi
        return 0
    fi
    if [[ "$ip" =~ ^[0-9a-fA-F:]+(/([0-9]{1,3}))?$ ]] && [[ "$ip" == *:* ]]; then
        local v6_prefix="${BASH_REMATCH[2]:-}"
        if [ -n "$v6_prefix" ] && [ "$v6_prefix" -gt 128 ]; then
            return 1
        fi
        return 0
    fi
    return 1
}

# Read database config from odbc.ini (same as generate-nftables.sh)
read_odbc_config() {
    local dsn="ss_admin"
    
    if [ -f "$ODBC_INI" ]; then
        DB_HOST=$(grep -A 20 "^\[$dsn\]" "$ODBC_INI" | grep "^Servername " | cut -d'=' -f2 | tr -d ' \r' | head -1 || true)
        DB_PORT=$(grep -A 20 "^\[$dsn\]" "$ODBC_INI" | grep "^Port " | cut -d'=' -f2 | tr -d ' \r' | head -1 || true)
        DB_USER=$(grep -A 20 "^\[$dsn\]" "$ODBC_INI" | grep "^Username " | cut -d'=' -f2 | tr -d ' \r' | head -1 || true)
        DB_PASS=$(grep -A 20 "^\[$dsn\]" "$ODBC_INI" | grep "^Password " | cut -d'=' -f2 | tr -d ' \r' | head -1 || true)
        DB_NAME=$(grep -A 20 "^\[$dsn\]" "$ODBC_INI" | grep "^Database " | cut -d'=' -f2 | tr -d ' \r' | head -1 || true)
    fi
    
    if [ -z "${DB_PASS:-}" ]; then
        if [ -f "/etc/softswitch/pbx-db-credentials" ]; then
            # shellcheck disable=SC1091
            . /etc/softswitch/pbx-db-credentials 2>/dev/null || true
            DB_PASS="${DB_PASSWORD:-${DB_PASS:-}}"
            DB_USER="${DB_USER:-pbx_user}"
        elif [ -f "/etc/softswitch/db-credentials" ]; then
            # shellcheck disable=SC1091
            . /etc/softswitch/db-credentials 2>/dev/null || true
            DB_PASS="${DB_PASSWORD:-${DB_PASS:-}}"
            DB_USER="${DB_USER:-pbx_user}"
        fi
    fi

    DB_HOST="${DB_HOST:-${PGHOST:-localhost}}"
    DB_PORT="${DB_PORT:-${PGPORT:-5432}}"
    DB_USER="${DB_USER:-${PGUSER:-pbx_user}}"
    DB_PASS="${DB_PASS:-${PGPASSWORD:-}}"
    DB_NAME="${DB_NAME:-${PGDATABASE:-ss_admin}}"
    
    export PGPASSWORD="$DB_PASS"
}

read_odbc_config

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1" >&2
}

check_fail2ban_installed() {
    if ! command -v fail2ban-client &> /dev/null; then
        log_warning "Fail2Ban is not installed. Installing..."
        apt-get update -qq
        apt-get install -y fail2ban
        log_info "Fail2Ban installed successfully"
    fi
}

get_firewall_settings() {
    local query_result
    local psql_exit_code=0
    query_result=$(psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" -t -A -F'|' -c "
        SELECT 
            intrusion_detection_enabled,
            failed_attempts_allowed,
            find_time,
            ban_time,
            COALESCE(notification_email, '') as notification_email
        FROM firewall_settings
        WHERE tenant_id = 1
        LIMIT 1;
    " 2>&1) || psql_exit_code=$?
    
    if [ $psql_exit_code -ne 0 ]; then
        log_error "Failed to query firewall settings from database: $query_result"
        echo ""
        return 1
    fi
    
    echo "$query_result"
}

build_trusted_ignoreip() {
    local base="127.0.0.1/8 ::1"
    local seen=" 127.0.0.1/8 ::1 "
    local candidate

    if [ -n "${FAIL2BAN_TRUSTED_IPS:-}" ]; then
        for candidate in $FAIL2BAN_TRUSTED_IPS; do
            if validate_ip_or_cidr "$candidate"; then
                if [[ "$seen" != *" ${candidate} "* ]]; then
                    base="${base} ${candidate}"
                    seen="${seen}${candidate} "
                fi
            else
                log_warning "Ignoring invalid entry in FAIL2BAN_TRUSTED_IPS: $candidate"
            fi
        done
    fi

    # Automatically honor active Access Control whitelist entries from PostgreSQL
    local db_whitelisted=""
    db_whitelisted=$(psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" -t -A -c "
        SELECT DISTINCT ip_address
        FROM access_control
        WHERE list_type = 'whitelist'
          AND enabled = true
          AND direction = 'input'
          AND ip_address IS NOT NULL
          AND ip_address <> '';
    " 2>/dev/null || true)

    if [ -n "$db_whitelisted" ]; then
        while IFS= read -r candidate; do
            candidate="$(trim_ws "${candidate:-}")"
            [ -z "$candidate" ] && continue
            if validate_ip_or_cidr "$candidate"; then
                if [[ "$seen" != *" ${candidate} "* ]]; then
                    base="${base} ${candidate}"
                    seen="${seen}${candidate} "
                fi
            else
                log_warning "Ignoring invalid whitelisted IP/CIDR from access_control: $candidate"
            fi
        done <<< "$db_whitelisted"
    fi

    printf '%s' "$base"
}

ensure_log_files_exist() {
    mkdir -p /var/log/nginx /var/log/freeswitch
    touch /var/log/nginx/softswitch_ssl_error.log \
          /var/log/nginx/softswitch_error.log \
          /var/log/nginx/error.log \
          /var/log/freeswitch/freeswitch.log \
          /var/log/fail2ban.log
}

generate_fail2ban_config() {
    log_info "Generating Fail2Ban configuration from database..."
    
    local settings=""
    local get_settings_exit_code=0
    settings=$(get_firewall_settings) || get_settings_exit_code=$?
    
    if [ $get_settings_exit_code -ne 0 ] || [ -z "$settings" ]; then
        log_error "Failed to retrieve firewall settings from database"
        return 1
    fi
    
    IFS='|' read -r enabled maxretry findtime bantime email <<< "$settings"
    
    enabled="$(trim_ws "${enabled:-}")"
    maxretry="$(trim_ws "${maxretry:-5}")"
    findtime="$(trim_ws "${findtime:-600}")"
    bantime="$(trim_ws "${bantime:-3600}")"
    email="$(trim_ws "${email:-}")"

    [[ "$maxretry" =~ ^[0-9]+$ ]] || maxretry=5
    [[ "$findtime" =~ ^[0-9]+$ ]] || findtime=600
    [[ "$bantime" =~ ^[0-9]+$ ]] || bantime=3600

    if [ -n "$email" ] && ! [[ "$email" =~ ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$ ]]; then
        log_warning "Invalid notification_email format rejected; disabling email alerts"
        email=""
    fi

    local ignore_ips
    ignore_ips="$(build_trusted_ignoreip)"
    
    if [ "$enabled" != "t" ] && [ "$enabled" != "true" ]; then
        log_info "Intrusion detection is disabled in database"
        if [ -f "${FAIL2BAN_DIR}/filter.d/freeswitch-sip.conf" ]; then
            rm -f "${FAIL2BAN_DIR}/filter.d/freeswitch-sip.conf"
            log_info "Removed FreeSWITCH SIP filter"
        fi
        mkdir -p "$FAIL2BAN_DIR"
        cat > "$JAIL_LOCAL" << EOF
# Ring2All PBX - Fail2Ban Configuration (Intrusion Detection Disabled)
# Auto-generated: $(date '+%Y-%m-%d %H:%M:%S')
# Only SSH protection is active. Enable Intrusion Detection in UI for SIP protection.

[DEFAULT]
ignoreip = ${ignore_ips}

banaction = nftables-multiport
banaction_allports = nftables-allports
backend = systemd

[sshd]
enabled = true
port = ssh
logpath = %(sshd_log)s
backend = %(sshd_backend)s
maxretry = 5
findtime = 600
bantime = 3600
EOF
        log_info "Generated minimal jail.local (SSH only)"
        if systemctl is-active --quiet fail2ban; then
            systemctl reload fail2ban
        fi
        return 0
    fi
    
    log_info "Intrusion detection is enabled"
    log_info "Settings: maxretry=$maxretry, findtime=${findtime}s, bantime=${bantime}s"
    
    mkdir -p "$FAIL2BAN_DIR"
    mkdir -p "${FAIL2BAN_DIR}/filter.d"
    ensure_log_files_exist
    
    cat > "${FAIL2BAN_DIR}/filter.d/freeswitch-sip.conf" <<'FILTER_EOF'
# Fail2Ban filter for FreeSWITCH SIP authentication failures
# Matches failed registration attempts in FreeSWITCH logs

[Definition]

_daemon = freeswitch

failregex = \[WARNING\]\s+sofia_reg\.c:\d+\s+SIP\s+auth\s+failure.*from\s+ip\s+<HOST>
            \[WARNING\]\s+sofia_reg\.c:\d+\s+Can.t\s+find\s+user.*from\s+<HOST>
            \[WARNING\]\s+sofia_reg\.c:\d+\s+Registration\s+Failed.*from\s+<HOST>
            \[WARNING\]\s+sofia\.c:\d+\s+Can.t\s+find\s+user.*from\s+<HOST>
            \[WARNING\]\s+mod_sofia\.c:\d+\s+.*AUTH\s+FAILED.*<HOST>
            \[WARNING\]\s+sofia\.c:\d+\s+IP\s+<HOST>\s+Rejected\s+by\s+acl.*
            \[WARNING\]\s+switch_core_state_machine\.c:\d+\s+\S+\s+sofia/\S+@<HOST>\s+Abandoned

ignoreregex =
FILTER_EOF
    log_info "Created FreeSWITCH SIP filter: ${FAIL2BAN_DIR}/filter.d/freeswitch-sip.conf"

    cat > "${FAIL2BAN_DIR}/filter.d/nginx-login-limit.conf" <<'LOGIN_FILTER_EOF'
# Fail2Ban filter for Ring2All Nginx login brute-force rate limiting
# Matches ONLY zone "login_limit" rejections so normal authenticated API/dashboard
# bursts (zone "api_limit") return graceful HTTP 429 without firewall-banning users or NAT offices.

[Definition]

failregex = ^\s*\S+\s+\S+\s+\[error\]\s+\d+#\d+:\s+\*\d+\s+limiting requests, excess: [0-9.]+ by zone "login_limit", client: <HOST>,

ignoreregex =
LOGIN_FILTER_EOF
    log_info "Created Nginx login-limit filter: ${FAIL2BAN_DIR}/filter.d/nginx-login-limit.conf"
    
    local email_block
    if [ -n "$email" ]; then
        local sender_host
        sender_host="$(hostname -f 2>/dev/null || hostname)"
        sender_host="$(printf '%s' "$sender_host" | tr -cd 'A-Za-z0-9.-')"
        [ -z "$sender_host" ] && sender_host="localhost"
        email_block="destemail = ${email}
sender = fail2ban@${sender_host}
action = %(action_mwl)s"
    else
        email_block="# No email configured - notifications disabled
action = %(action_)s"
    fi
    
    cat > "$JAIL_LOCAL" << EOF
# =====================================================
# Ring2All PBX - Fail2Ban Configuration
# Auto-generated: $(date '+%Y-%m-%d %H:%M:%S')
# =====================================================
# This file is auto-generated from database settings
# Do not edit manually - changes will be overwritten
# =====================================================

[DEFAULT]
ignoreip = ${ignore_ips}

banaction = nftables-multiport
banaction_allports = nftables-allports

# Email notifications
${email_block}

# Global settings from database
maxretry = $maxretry
findtime = $findtime
bantime = $bantime

# Backend
backend = systemd

# Logging
loglevel = INFO
logtarget = /var/log/fail2ban.log

# =====================================================
# SSH Jail
# =====================================================
[sshd]
enabled = true
port = ssh
logpath = %(sshd_log)s
backend = %(sshd_backend)s
maxretry = $maxretry
findtime = $findtime
bantime = $bantime

# =====================================================
# HTTP/HTTPS Jails
# =====================================================
[nginx-http-auth]
enabled = false
port = http,https
logpath = /var/log/nginx/error.log

[nginx-limit-req]
enabled = true
port = http,https
filter = nginx-login-limit
logpath = /var/log/nginx/softswitch_ssl_error.log
          /var/log/nginx/softswitch_error.log
          /var/log/nginx/error.log
backend = auto
maxretry = 10
findtime = $findtime
bantime = $bantime

# =====================================================
# PostgreSQL Jail (optional)
# =====================================================
[postgresql]
enabled = false
port = 5432
logpath = /var/log/postgresql/postgresql-*.log
maxretry = 5

# =====================================================
# FreeSWITCH SIP Jail (UDP + TCP + TLS allports protection)
# =====================================================
[freeswitch-sip]
enabled = true
port = 5060,5061,5080,5081
protocol = all
banaction = %(banaction_allports)s
filter = freeswitch-sip
logpath = /var/log/freeswitch/freeswitch.log
backend = auto
maxretry = $maxretry
findtime = $findtime
bantime = $bantime

# =====================================================
# Recidive Jail
# =====================================================
[recidive]
enabled = true
logpath = /var/log/fail2ban.log
banaction = %(banaction_allports)s
bantime = 1w
findtime = 1d
maxretry = 2

EOF

    log_info "Fail2Ban configuration generated: $JAIL_LOCAL"
    
    # Validate configuration using fail2ban-client -t exit code
    if ! fail2ban-client -t >/dev/null 2>&1; then
        log_error "Fail2Ban configuration validation failed"
        fail2ban-client -t || true
        return 1
    fi
    
    log_info "Fail2Ban configuration validated successfully"
    return 0
}

ban_ip_nft() {
    local IP="${1:-}"
    if ! validate_ip_or_cidr "$IP"; then
        log_error "Rejected invalid IP/CIDR for ban: $IP"
        return 1
    fi
    if [[ "$IP" == *:* ]]; then
        nft add element inet filter manual_blacklist_v6 "{ $IP }" 2>/dev/null || true
    else
        nft add element inet filter manual_blacklist_v4 "{ $IP }" 2>/dev/null || true
    fi
    log_info "Banned IP in nftables: $IP"
}

unban_ip_nft() {
    local IP="${1:-}"
    if ! validate_ip_or_cidr "$IP"; then
        log_error "Rejected invalid IP/CIDR for unban: $IP"
        return 1
    fi
    if [[ "$IP" == *:* ]]; then
        nft delete element inet filter manual_blacklist_v6 "{ $IP }" 2>/dev/null || true
    else
        nft delete element inet filter manual_blacklist_v4 "{ $IP }" 2>/dev/null || true
    fi
    fail2ban-client unban "$IP" >/dev/null 2>&1 || true
    log_info "Unbanned IP: $IP"
}

apply_fail2ban_config() {
    log_info "Applying Fail2Ban configuration..."
    
    if ! generate_fail2ban_config; then
        log_error "Failed to generate Fail2Ban configuration"
        return 1
    fi
    
    if systemctl is-active --quiet fail2ban; then
        log_info "Reloading Fail2Ban service..."
        systemctl reload fail2ban
    else
        log_info "Starting Fail2Ban service..."
        systemctl enable fail2ban
        systemctl start fail2ban
    fi
    
    sleep 2
    
    if systemctl is-active --quiet fail2ban; then
        log_info "Fail2Ban service is running"
        log_info "Fail2Ban status:"
        fail2ban-client status | head -10
        return 0
    else
        log_error "Fail2Ban service failed to start"
        systemctl status fail2ban --no-pager -l
        return 1
    fi
}

main() {
    local command="${1:-apply}"
    
    case "$command" in
        generate)
            check_fail2ban_installed
            generate_fail2ban_config
            ;;
        apply)
            check_fail2ban_installed
            apply_fail2ban_config
            ;;
        ban)
            ban_ip_nft "${2:-}"
            ;;
        unban)
            unban_ip_nft "${2:-}"
            ;;
        status)
            if systemctl is-active --quiet fail2ban; then
                log_info "Fail2Ban is running"
                fail2ban-client status
            else
                log_warning "Fail2Ban is not running"
            fi
            ;;
        stop)
            log_info "Stopping Fail2Ban..."
            systemctl stop fail2ban
            systemctl disable fail2ban
            ;;
        start)
            check_fail2ban_installed
            apply_fail2ban_config
            ;;
        *)
            echo "Usage: $0 {generate|apply|ban <ip>|unban <ip>|status|start|stop}"
            exit 1
            ;;
    esac
}

main "$@"
