#!/usr/bin/env bash
# ──────────────────────────────────────────────────────────────
#  simulate_failed_logins.sh
#
#  Writes synthetic authentication-failure log lines to a file
#  that matches the manual-Jail fail2ban filter.
#
#  Usage:
#    bash Docker/simulate_failed_logins.sh [COUNT] [SOURCE_IP] [LOG_FILE]
#
#  Defaults:
#    COUNT    : 5
#    SOURCE_IP: 192.168.100.99
#    LOG_FILE : Docker/logs/auth.log       (relative to repo root)
#
#  Log line format (must match manual-Jail failregex exactly):
#    YYYY-MM-DD HH:MM:SS bangui-auth: authentication failure from <IP>
# ──────────────────────────────────────────────────────────────

set -euo pipefail

# ── Defaults ──────────────────────────────────────────────────
readonly DEFAULT_COUNT=5
readonly DEFAULT_IP="192.168.100.99"

# Resolve script location so defaults work regardless of cwd.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly DEFAULT_LOG_FILE="${SCRIPT_DIR}/logs/auth.log"

# ── Arguments ─────────────────────────────────────────────────
COUNT="${1:-${DEFAULT_COUNT}}"
SOURCE_IP="${2:-${DEFAULT_IP}}"
LOG_FILE="${3:-${DEFAULT_LOG_FILE}}"

# ── Validate COUNT is a positive integer ──────────────────────
if ! [[ "${COUNT}" =~ ^[1-9][0-9]*$ ]]; then
    echo "ERROR: COUNT must be a positive integer, got: '${COUNT}'" >&2
    exit 1
fi

# ── Ensure log directory exists ───────────────────────────────
LOG_DIR="$(dirname "${LOG_FILE}")"
mkdir -p "${LOG_DIR}"

# ── Write failure lines ───────────────────────────────────────
echo "Writing ${COUNT} authentication-failure line(s) for ${SOURCE_IP} to ${LOG_FILE} ..."

for ((i = 1; i <= COUNT; i++)); do
    TIMESTAMP="$(date '+%Y-%m-%d %H:%M:%S')"
    printf '%s bangui-auth: authentication failure from %s\n' \
        "${TIMESTAMP}" "${SOURCE_IP}" >> "${LOG_FILE}"
    sleep 0.5
done

# ── Summary ───────────────────────────────────────────────────
echo "Done."
echo "  Lines written : ${COUNT}"
echo "  Source IP     : ${SOURCE_IP}"
echo "  Log file      : ${LOG_FILE}"
