#!/bin/bash

THRESHOLD=5
CHECK_INTERVAL=300  # 5 minutes
ALERT_EMAIL="<user>@devsecops.local"
GITLAB_LOG="/srv/gitlab/logs/gitlab-rails/application_json.log"

send_alert() {
    local failed_count=$1
    local recent_failures=$2
    echo "WARNING: $failed_count failed login attempts in the last 5 minutes
Time: $(date)

Recent failures:
$recent_failures" | mail -s "GitLab Security Alert - Failed Logins" "$ALERT_EMAIL"
}

monitor_failed_logins() {
    if [ ! -f "$GITLAB_LOG" ]; then
        echo "Error: GitLab log file not found at $GITLAB_LOG"
        exit 1
    fi
    
    # Get current timestamp
    local current_time=$(date +%s)
    local window_start=$((current_time - CHECK_INTERVAL))
    
    # Format window start time for comparison
    local window_start_iso=$(date -u -d "@$window_start" +"%Y-%m-%dT%H:%M:%S")
    
    # Count failed logins in last 5 minutes
    local recent_failures=$(grep "Failed Login:" "$GITLAB_LOG" | while read -r line; do
        log_time=$(echo "$line" | jq -r '.time' | cut -d'.' -f1)
        if [[ "$log_time" > "$window_start_iso" ]]; then
            echo "$line"
        fi
    done)
    
    local failed_count=$(echo "$recent_failures" | grep -c "Failed Login:")
    if [ "$failed_count" -gt "$THRESHOLD" ]; then
        send_alert "$failed_count" "$(echo "$recent_failures" | jq -r '.message')"
    fi
}

while true; do
    monitor_failed_logins
    sleep "$CHECK_INTERVAL"
done
