#!/usr/bin/env python

from __future__ import print_function

import os
import sys
import subprocess
import tempfile
import shutil
import stat
import time
import fcntl
from datetime import datetime

SOURCES = ("firewall", "messages", "suricata", "squid", "urlfilter")
if len(sys.argv) < 2 or sys.argv[1] not in SOURCES:
    print("Usage: %s {%s} [--maintenance]" % (sys.argv[0], "|".join(SOURCES)), file=sys.stderr)
    sys.exit(2)

WORKER_SOURCE = sys.argv[1]
MAINTENANCE_ONLY = "--maintenance" in sys.argv[2:]

# ============================================================
# CONFIGURATION - Read from /etc/log2db/log2db.conf
# ============================================================
CONFIG_FILE = "/etc/log2db/log2db.conf"

# Default values
LOG_ENABLED = True
LOG_LEVEL = "INFO"
LOG_DIR = "/var/log/log2db"
LOG_FILE = os.path.join(LOG_DIR, "log2db.log")

def load_config():
    """Load configuration from config file"""
    global LOG_ENABLED, LOG_LEVEL, LOG_DIR, LOG_FILE
    
    if not os.path.exists(CONFIG_FILE):
        return  # Use defaults
    
    try:
        with open(CONFIG_FILE, "r") as f:
            for line in f:
                line = line.strip()
                if not line or line.startswith("#"):
                    continue
                if "=" in line:
                    key, value = line.split("=", 1)
                    key = key.strip()
                    value = value.strip().strip('"').strip("'")
                    
                    if key == "LOG_ENABLED":
                        LOG_ENABLED = value.lower() == "true"
                    elif key == "LOG_LEVEL":
                        LOG_LEVEL = value.upper()
                    elif key == "LOG_DIR":
                        LOG_DIR = value
                    elif key == "LOG_FILE":
                        LOG_FILE = value
    except Exception:
        pass  # Use defaults on error

load_config()

# Ensure log directory exists
if not os.path.exists(LOG_DIR):
    try:
        os.makedirs(LOG_DIR)
    except OSError:
        pass

def log_message(level, message):
    """Write log message to file if logging is enabled"""
    if not LOG_ENABLED:
        return
    if level == "DEBUG" and LOG_LEVEL != "DEBUG":
        return
    if level == "INFO" and LOG_LEVEL not in ("DEBUG", "INFO"):
        return
    if level == "WARNING" and LOG_LEVEL not in ("DEBUG", "INFO", "WARNING"):
        return
    if level == "ERROR":
        pass  # Always log errors

    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    log_line = "[%s] [%s] %s\n" % (timestamp, level, message)
    try:
        with open(LOG_FILE, "a") as f:
            f.write(log_line)
    except IOError:
        pass  # Silently fail if can't write log

def log_info(msg):
    log_message("INFO", msg)
    print(msg)

def log_warning(msg):
    log_message("WARNING", msg)
    print("[!] Warning: %s" % msg)

def log_error(msg):
    log_message("ERROR", msg)
    print("[-] Error: %s" % msg, file=sys.stderr)

def log_debug(msg):
    log_message("DEBUG", msg)

# ============================================================
# LOCK MECHANISM
# ============================================================
LOCK_FILE = "/var/duckdb/logs-ingest-%s.lock" % WORKER_SOURCE
LOCK_HANDLE = None

def acquire_lock():
    global LOCK_HANDLE
    LOCK_HANDLE = open(LOCK_FILE, "w")
    try:
        fcntl.flock(LOCK_HANDLE.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
    except IOError:
        log_warning("Another %s worker is already running. Skipping this cycle." % WORKER_SOURCE)
        LOCK_HANDLE.close()
        LOCK_HANDLE = None
        sys.exit(0)
    LOCK_HANDLE.write(str(os.getpid()))
    LOCK_HANDLE.flush()

def release_lock():
    global LOCK_HANDLE
    if LOCK_HANDLE is not None:
        fcntl.flock(LOCK_HANDLE.fileno(), fcntl.LOCK_UN)
        LOCK_HANDLE.close()
        LOCK_HANDLE = None

# ============================================================
# RETENTION SETTINGS
# ============================================================
DEFAULT_LOG2DB_KEEP_HISTORY = 56
LOG2DB_SETTINGS_FILE = "/var/efw/logging/settings"
LOG2DB_DEFAULT_SETTINGS_FILE = "/usr/lib/efw/logging/default/settings"

def read_setting_int(path, key):
    """Return an integer setting from a key=value file, or None if absent/empty/invalid."""
    if not os.path.exists(path):
        return None
    try:
        with open(path, "r") as f:
            for line in f:
                line = line.strip()
                if line.startswith(key + "="):
                    val = line.split("=", 1)[1].strip().strip('"').strip("'")
                    if not val:
                        return None
                    return int(val)
    except Exception as e:
        log_warning("Could not read setting %s from %s: %s" % (key, path, e))
    return None

def get_log2db_keep_days(default_days=DEFAULT_LOG2DB_KEEP_HISTORY):
    for path in (LOG2DB_SETTINGS_FILE, LOG2DB_DEFAULT_SETTINGS_FILE):
        days = read_setting_int(path, "LOG2DB_KEEP_HISTORY")
        if days is not None and days >= 0:
            return days
    return default_days

# ============================================================
# MAIN EXECUTION
# ============================================================
acquire_lock()

log_info("Starting %s %s process..." % (WORKER_SOURCE, "maintenance" if MAINTENANCE_ONLY else "ingestion"))
start_time = time.time()

CURRENT_YEAR    = datetime.now().year
DB_FIREWALL     = os.path.join("/var/duckdb", "firewall.db")
DB_MESSAGES     = os.path.join("/var/duckdb", "messages.db")
DB_SURICATA     = os.path.join("/var/duckdb", "suricata.db")
DB_SQUID        = os.path.join("/var/duckdb", "squid.db")
DB_URLFILTER    = os.path.join("/var/duckdb", "urlfilter.db")

OFFSET_FILE      = os.path.join("/var/duckdb", "firewall.offset")
TMP_LOG          = os.path.join("/var/duckdb", "firewall_delta.log")
MSG_OFFSET_FILE  = os.path.join("/var/duckdb", "messages.offset")
TMP_MSG_LOG      = os.path.join("/var/duckdb", "messages_delta.log")
SURI_OFFSET_FILE = os.path.join("/var/duckdb", "suricata.offset")
TMP_SURI_LOG     = os.path.join("/var/duckdb", "suricata_delta.log")
SQUID_OFFSET_FILE = os.path.join("/var/duckdb", "squid.offset")
TMP_SQUID_LOG    = os.path.join("/var/duckdb", "squid_delta.log")
URLFILTER_OFFSET_FILE = os.path.join("/var/duckdb", "urlfilter.offset")
TMP_URLFILTER_LOG = os.path.join("/var/duckdb", "urlfilter_delta.log")

GEOIP_BASE = "/usr/lib/geoip"

def find_geoip_csv_dir(base):
    candidates = []
    for dirpath, dirnames, _ in os.walk(base):
        for d in dirnames:
            if d.startswith("GeoLite2-Country-CSV_"):
                candidates.append(os.path.join(dirpath, d))
    return sorted(candidates, reverse=True)[0] if candidates else None

GEOIP_CSV_DIR = find_geoip_csv_dir(GEOIP_BASE) if WORKER_SOURCE in ("firewall", "suricata") else None
GEOIP_BLOCKS_V4 = None
GEOIP_LOCATIONS = None
GEOIP_VERSION_TAG = "NONE"

if WORKER_SOURCE in ("firewall", "suricata") and not GEOIP_CSV_DIR:
    log_warning("GeoLite2-Country-CSV directory not found under %s. Geolocation will be skipped." % GEOIP_BASE)
elif GEOIP_CSV_DIR:
    GEOIP_BLOCKS_V4 = os.path.join(GEOIP_CSV_DIR, "GeoLite2-Country-Blocks-IPv4.csv")
    GEOIP_LOCATIONS = os.path.join(GEOIP_CSV_DIR, "GeoLite2-Country-Locations-en.csv")
    GEOIP_VERSION_TAG = os.path.basename(GEOIP_CSV_DIR)
    log_info("MaxMind GeoIP database identified: %s" % GEOIP_VERSION_TAG)

DUCKDB_BIN = "/usr/bin/duckdb"
if not os.path.isfile(DUCKDB_BIN) or not os.access(DUCKDB_BIN, os.X_OK):
    log_error("Critical Error: duckdb not found at /usr/bin/duckdb")
    release_lock()
    sys.exit(1)

detected_cpus = os.cpu_count() if hasattr(os, "cpu_count") else 1
if not hasattr(os, "cpu_count"):
    try:
        import multiprocessing
        detected_cpus = multiprocessing.cpu_count()
    except Exception:
        detected_cpus = 1
default_threads = max(1, detected_cpus // 2)
DUCKDB_THREADS = max(1, int(os.environ.get("LOG2DB_THREADS", default_threads)))
GEOIP_THREADS = max(1, int(os.environ.get("LOG2DB_GEOIP_THREADS", detected_cpus)))

log_debug("Using %d threads for DuckDB" % DUCKDB_THREADS)

def run_logtail(log_file, offset_file, output_file):
    if not os.path.exists(log_file):
        with open(output_file, "w"):
            pass
        log_info("Log file %s not found; waiting for logs." % log_file)
        return

    pending_offset = offset_file + ".pending"
    if os.path.exists(offset_file):
        shutil.copyfile(offset_file, pending_offset)
    elif os.path.exists(pending_offset):
        os.remove(pending_offset)

    with open(output_file, "w") as out:
        with open(os.devnull, "w") as devnull:
            try:
                status = subprocess.call(
                    ["logtail", "-f", log_file, "-o", pending_offset],
                    stdout=out,
                    stderr=devnull,
                )
                if status != 0:
                    log_error("Critical Error: logtail failed for %s with status %d." % (log_file, status))
                    release_lock()
                    sys.exit(1)
            except OSError as e:
                log_error("Critical Error: 'logtail' binary not found or failed to execute (%s)." % e)
                release_lock()
                sys.exit(1)

def commit_offset(offset_file):
    pending_offset = offset_file + ".pending"
    if os.path.exists(pending_offset):
        os.rename(pending_offset, offset_file)


def ensure_schema():
    """Create the selected database and its empty schema before reading logs."""
    schemas = {
        "firewall": (DB_FIREWALL, """
            CREATE TABLE IF NOT EXISTS log_firewall (
                event_date TIMESTAMP,
                src_ip VARCHAR,
                dst_ip VARCHAR,
                dst_port INTEGER,
                interface VARCHAR,
                protocol VARCHAR,
                action VARCHAR,
                chain VARCHAR,
                src_country_code VARCHAR,
                src_country_name VARCHAR,
                dst_country_code VARCHAR,
                dst_country_name VARCHAR
            );
            CREATE TABLE IF NOT EXISTS geoip_metadata (version VARCHAR);
            CREATE TABLE IF NOT EXISTS geoip_cache (
                ip_start BIGINT,
                ip_end BIGINT,
                country_code VARCHAR,
                country_name VARCHAR
            );
        """),
        "messages": (DB_MESSAGES, """
            CREATE TABLE IF NOT EXISTS log_messages (
                event_date TIMESTAMP,
                service VARCHAR,
                message VARCHAR
            );
        """),
        "suricata": (DB_SURICATA, """
            CREATE TABLE IF NOT EXISTS log_suricata (
                event_date TIMESTAMP,
                action VARCHAR,
                sid INTEGER,
                signature VARCHAR,
                classification VARCHAR,
                priority INTEGER,
                protocol VARCHAR,
                src_ip VARCHAR,
                src_port INTEGER,
                dst_ip VARCHAR,
                dst_port INTEGER,
                src_country_code VARCHAR,
                src_country_name VARCHAR,
                dst_country_code VARCHAR,
                dst_country_name VARCHAR
            );
            CREATE TABLE IF NOT EXISTS geoip_metadata (version VARCHAR);
            CREATE TABLE IF NOT EXISTS geoip_cache (
                ip_start BIGINT,
                ip_end BIGINT,
                country_code VARCHAR,
                country_name VARCHAR
            );
        """),
        "urlfilter": (DB_URLFILTER, """
            CREATE TABLE IF NOT EXISTS log_urlfilter (
                event_date TIMESTAMP,
                src_ip VARCHAR,
                username VARCHAR,
                method VARCHAR,
                http_status INTEGER,
                url VARCHAR,
                domain VARCHAR,
                category VARCHAR,
                action_category VARCHAR,
                action VARCHAR
            );
        """),
        "squid": (DB_SQUID, """
            CREATE TABLE IF NOT EXISTS log_squid (
                event_date TIMESTAMP,
                elapsed_ms BIGINT,
                src_ip VARCHAR,
                result VARCHAR,
                http_status INTEGER,
                bytes BIGINT,
                method VARCHAR,
                url VARCHAR,
                username VARCHAR,
                hierarchy VARCHAR,
                destination_ip VARCHAR,
                mime_type VARCHAR,
                http_status_description VARCHAR,
                access_verdict VARCHAR
            );
            ALTER TABLE log_squid ADD COLUMN IF NOT EXISTS http_status_description VARCHAR;
            ALTER TABLE log_squid ADD COLUMN IF NOT EXISTS access_verdict VARCHAR;
        """),
    }
    db_path, schema_sql = schemas[WORKER_SOURCE]
    proc = subprocess.Popen(
        [DUCKDB_BIN, db_path],
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    )
    _, stderr_out = proc.communicate(input=schema_sql.encode("utf-8"))
    if proc.returncode != 0:
        log_error("Unable to initialize %s schema:\n%s" % (
            os.path.basename(db_path), stderr_out.decode("utf-8", errors="replace")))
        release_lock()
        sys.exit(1)
    log_info("Database schema ready in %s." % os.path.basename(db_path))


ensure_schema()

if not MAINTENANCE_ONLY:
    log_info("Collecting new %s log entries using logtail..." % WORKER_SOURCE)
    if WORKER_SOURCE == "firewall":
        run_logtail("/var/log/firewall", OFFSET_FILE, TMP_LOG)
    elif WORKER_SOURCE == "messages":
        run_logtail("/var/log/messages", MSG_OFFSET_FILE, TMP_MSG_LOG)
    elif WORKER_SOURCE == "suricata":
        run_logtail("/var/log/suricata/alerts.log", SURI_OFFSET_FILE, TMP_SURI_LOG)
    elif WORKER_SOURCE == "squid":
        run_logtail("/var/log/squid/access.log", SQUID_OFFSET_FILE, TMP_SQUID_LOG)
    elif WORKER_SOURCE == "urlfilter":
        run_logtail("/var/log/c-icap/access.log", URLFILTER_OFFSET_FILE, TMP_URLFILTER_LOG)

fw_size   = os.path.getsize(TMP_LOG) if WORKER_SOURCE == "firewall" and not MAINTENANCE_ONLY and os.path.exists(TMP_LOG) else 0
msg_size  = os.path.getsize(TMP_MSG_LOG) if WORKER_SOURCE == "messages" and not MAINTENANCE_ONLY and os.path.exists(TMP_MSG_LOG) else 0
suri_size = os.path.getsize(TMP_SURI_LOG) if WORKER_SOURCE == "suricata" and not MAINTENANCE_ONLY and os.path.exists(TMP_SURI_LOG) else 0
squid_size = os.path.getsize(TMP_SQUID_LOG) if WORKER_SOURCE == "squid" and not MAINTENANCE_ONLY and os.path.exists(TMP_SQUID_LOG) else 0
urlfilter_size = os.path.getsize(TMP_URLFILTER_LOG) if WORKER_SOURCE == "urlfilter" and not MAINTENANCE_ONLY and os.path.exists(TMP_URLFILTER_LOG) else 0

log_debug("Delta sizes - Firewall: %d bytes, Messages: %d bytes, Suricata: %d bytes, Squid: %d bytes, URL Filter: %d bytes" % (fw_size, msg_size, suri_size, squid_size, urlfilter_size))

fw_status = 0 if MAINTENANCE_ONLY and WORKER_SOURCE == "firewall" else -1
if fw_size > 0:
    log_info("Importing Firewall log delta (%d bytes) into firewall.db..." % fw_size)
    SQL_FIREWALL = """
    PRAGMA threads=%(DUCKDB_THREADS)s;

    CREATE TABLE IF NOT EXISTS log_firewall (
        event_date TIMESTAMP,
        src_ip VARCHAR,
        dst_ip VARCHAR,
        dst_port INTEGER,
        interface VARCHAR,
        protocol VARCHAR,
        action VARCHAR,
        chain VARCHAR,
        src_country_code VARCHAR,
        src_country_name VARCHAR,
        dst_country_code VARCHAR,
        dst_country_name VARCHAR
    );

    WITH fw_lines AS (
        SELECT unnest(string_split_regex(content, '\\r?\\n')) AS line
        FROM read_text('%(TMP_LOG)s')
    ),
    new_fw AS (
        SELECT
            try_strptime('%(CURRENT_YEAR)s ' || substring(line, 1, 15), '%%Y %%b %%d %%H:%%M:%%S') AS event_date,
            string_split(string_split(line, 'SRC=')[2], ' ')[1] AS src_ip,
            string_split(string_split(line, 'DST=')[2], ' ')[1] AS dst_ip,
            CASE
                WHEN line LIKE '%%DPT=%%' THEN
                    TRY_CAST(string_split(string_split(line, 'DPT=')[2], ' ')[1] AS INTEGER)
                ELSE NULL
            END AS dst_port,
            CASE WHEN line LIKE '%%IN=%%'    THEN string_split(string_split(line, 'IN=')[2],    ' ')[1] ELSE NULL END AS interface,
            CASE WHEN line LIKE '%%PROTO=%%' THEN string_split(string_split(line, 'PROTO=')[2], ' ')[1] ELSE NULL END AS protocol,
            UPPER(COALESCE(
                regexp_extract(line, 'ulogd\\[\\d+\\]:\\s*([A-Z]+):([A-Z]+)', 2), 
                regexp_extract(line, 'ulogd\\[\\d+\\]:\\s*([A-Z]+):([A-Z]+)', 1), 
                'DROP'
            )) AS action,
            regexp_extract(line, 'ulogd\\[\\d+\\]:\\s*([A-Z]+)', 1) AS chain
        FROM fw_lines
        WHERE line IS NOT NULL
          AND line != ''
          AND line LIKE '%%SRC=%%'
    )
    INSERT INTO log_firewall (
        event_date, src_ip, dst_ip, dst_port, interface, protocol, action, chain,
        src_country_code, src_country_name, dst_country_code, dst_country_name
    )
    SELECT DISTINCT
        n.event_date, n.src_ip, n.dst_ip, n.dst_port, n.interface, n.protocol, n.action, n.chain,
        'PENDING' AS src_country_code, 'Processing...' AS src_country_name,
        'PENDING' AS dst_country_code, 'Processing...' AS dst_country_name
    FROM new_fw n
    WHERE n.event_date IS NOT NULL
      AND NOT EXISTS (
          SELECT 1 FROM log_firewall e
          WHERE e.event_date = n.event_date
            AND COALESCE(e.src_ip, '') = COALESCE(n.src_ip, '')
            AND COALESCE(e.dst_ip, '') = COALESCE(n.dst_ip, '')
            AND COALESCE(e.dst_port, 0) = COALESCE(n.dst_port, 0)
            AND COALESCE(e.protocol, '') = COALESCE(n.protocol, '')
            AND COALESCE(e.action, '') = COALESCE(n.action, '')
      );
    """ % {
        "TMP_LOG":        TMP_LOG,
        "CURRENT_YEAR":   CURRENT_YEAR,
        "DUCKDB_THREADS": DUCKDB_THREADS,
    }

    tmp_sql_fd, tmp_sql_path = tempfile.mkstemp(suffix=".sql")
    try:
        with os.fdopen(tmp_sql_fd, "w") as tmp_sql_file:
            tmp_sql_file.write(SQL_FIREWALL)
        with open(tmp_sql_path, "r") as sql_input:
            proc = subprocess.Popen([DUCKDB_BIN, DB_FIREWALL], stdin=sql_input, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            _, stderr_out = proc.communicate()
            fw_status = proc.returncode
    finally:
        if os.path.exists(tmp_sql_path):
            os.remove(tmp_sql_path)
    if fw_status != 0:
        log_error("Firewall ingestion error:\n%s" % stderr_out.decode("utf-8", errors="replace"))
if WORKER_SOURCE == "firewall" and not MAINTENANCE_ONLY:
    if fw_status == 0 or fw_size == 0:
        commit_offset(OFFSET_FILE)
    else:
        log_warning("Firewall offset was not advanced; the delta will be retried.")
    if fw_size == 0:
        fw_status = 0
        log_info("No new Firewall logs to process.")

msg_status = 0 if MAINTENANCE_ONLY and WORKER_SOURCE == "messages" else -1
if msg_size > 0:
    log_info("Importing OS log delta (%d bytes) into messages.db..." % msg_size)
    SQL_MESSAGES = """
    PRAGMA threads=%(DUCKDB_THREADS)s;

    CREATE TABLE IF NOT EXISTS log_messages (
        event_date TIMESTAMP,
        service VARCHAR,
        message VARCHAR
    );

    CREATE OR REPLACE TEMP TABLE temp_msg_lines AS
    SELECT unnest(string_split_regex(content, '\\r?\\n')) AS line
    FROM read_text('%(TMP_MSG_LOG)s')
    WHERE content IS NOT NULL AND content != '';

    WITH parsed AS (
        SELECT
            strptime('%(CURRENT_YEAR)s ' || regexp_replace(substring(line, 1, 15), '\\s+', ' ', 'g'), '%%Y %%b %%d %%H:%%M:%%S') AS event_date,
            regexp_extract(line, '^[A-Za-z]{3}\\s+\\d+\\s+\\d{2}:\\d{2}:\\d{2}\\s+[^\\s]+\\s+([^:\\[]+)', 1) AS service,
            regexp_extract(line, '^[A-Za-z]{3}\\s+\\d+\\s+\\d{2}:\\d{2}:\\d{2}\\s+[^\\s]+\\s+[^:]+:\\s*(.*)$', 1) AS message
        FROM temp_msg_lines
        WHERE line IS NOT NULL
          AND line != ''
          AND length(line) > 16
    )
    INSERT INTO log_messages (event_date, service, message)
    SELECT p.event_date, p.service, p.message
    FROM parsed p
    WHERE p.event_date IS NOT NULL
      AND NOT EXISTS (
          SELECT 1 FROM log_messages e
          WHERE e.event_date = p.event_date
            AND COALESCE(e.service, '') = COALESCE(p.service, '')
            AND COALESCE(e.message, '') = COALESCE(p.message, '')
      );
    """ % {
        "TMP_MSG_LOG":    TMP_MSG_LOG,
        "CURRENT_YEAR":   CURRENT_YEAR,
        "DUCKDB_THREADS": DUCKDB_THREADS,
    }

    tmp_sql_fd, tmp_sql_path = tempfile.mkstemp(suffix=".sql")
    try:
        with os.fdopen(tmp_sql_fd, "w") as tmp_sql_file:
            tmp_sql_file.write(SQL_MESSAGES)
        with open(tmp_sql_path, "r") as sql_input:
            proc = subprocess.Popen([DUCKDB_BIN, DB_MESSAGES], stdin=sql_input, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            _, stderr_out = proc.communicate()
            msg_status = proc.returncode
    finally:
        if os.path.exists(tmp_sql_path):
            os.remove(tmp_sql_path)
    if msg_status != 0:
        log_error("Messages ingestion error:\n%s" % stderr_out.decode("utf-8", errors="replace"))
if WORKER_SOURCE == "messages" and not MAINTENANCE_ONLY:
    if msg_status == 0 or msg_size == 0:
        commit_offset(MSG_OFFSET_FILE)
    else:
        log_warning("Messages offset was not advanced; the delta will be retried.")
    if msg_size == 0:
        msg_status = 0
        log_info("No new system logs (messages) to process.")

suri_status = 0 if MAINTENANCE_ONLY and WORKER_SOURCE == "suricata" else -1
if suri_size > 0:
    log_info("Importing Suricata log delta (%d bytes) into suricata.db..." % suri_size)
    SQL_SURICATA = """
    PRAGMA threads=%(DUCKDB_THREADS)s;

    CREATE TABLE IF NOT EXISTS log_suricata (
        event_date TIMESTAMP,
        action VARCHAR,
        sid INTEGER,
        signature VARCHAR,
        classification VARCHAR,
        priority INTEGER,
        protocol VARCHAR,
        src_ip VARCHAR,
        src_port INTEGER,
        dst_ip VARCHAR,
        dst_port INTEGER,
        src_country_code VARCHAR,
        src_country_name VARCHAR,
        dst_country_code VARCHAR,
        dst_country_name VARCHAR
    );

    WITH suri_lines AS (
        SELECT unnest(string_split_regex(content, '\\r?\\n')) AS line
        FROM read_text('%(TMP_SURI_LOG)s')
        WHERE content IS NOT NULL AND content != ''
    ),
    parsed AS (
        SELECT
            COALESCE(
                TRY_STRPTIME(regexp_extract(line, '^([0-9]{2}/[0-9]{2}/[0-9]{4}-[0-9]{2}:[0-9]{2}:[0-9]{2})', 1), '%%m/%%d/%%Y-%%H:%%M:%%S'),
                date_trunc('second', CURRENT_TIMESTAMP)
            ) AS event_date,
            UPPER(COALESCE(NULLIF(regexp_extract(line, '\\[(Drop|Blocked|Allowed|Alert)\\]', 1), ''), 'ALERT')) AS action,
            TRY_CAST(regexp_extract(line, '\\[\\d+:(\\d+):\\d+\\]', 1) AS INTEGER) AS sid,
            regexp_extract(line, '\\[\\*\\*\\]\\s*\\[\\d+:\\d+:\\d+\\]\\s*(.*?)\\s*\\[\\*\\*\\]', 1) AS signature,
            regexp_extract(line, '\\[Classification:\\s*(.*?)\\]', 1) AS classification,
            TRY_CAST(regexp_extract(line, '\\[Priority:\\s*(\\d+)\\]', 1) AS INTEGER) AS priority,
            regexp_extract(line, '\\{([A-Za-z]+)\\}', 1) AS protocol,
            regexp_extract(line, '([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}):?\\d*\\s*->', 1) AS src_ip,
            TRY_CAST(regexp_extract(line, '([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}):(\\d+)\\s*->', 2) AS INTEGER) AS src_port,
            regexp_extract(line, '->\\s*([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3})', 1) AS dst_ip,
            TRY_CAST(regexp_extract(line, '->\\s*[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}:(\\d+)', 1) AS INTEGER) AS dst_port
        FROM suri_lines
    )
    INSERT INTO log_suricata (
        event_date, action, sid, signature, classification, priority,
        protocol, src_ip, src_port, dst_ip, dst_port,
        src_country_code, src_country_name, dst_country_code, dst_country_name
    )
    SELECT DISTINCT
        p.event_date, p.action, p.sid, p.signature, p.classification, p.priority,
        p.protocol, p.src_ip, p.src_port, p.dst_ip, p.dst_port,
        'PENDING' AS src_country_code, 'Processing...' AS src_country_name,
        'PENDING' AS dst_country_code, 'Processing...' AS dst_country_name
    FROM parsed p
    WHERE p.event_date IS NOT NULL
      AND p.signature IS NOT NULL AND p.signature != ''
      AND (p.src_ip IS NOT NULL AND p.src_ip != '' OR p.dst_ip IS NOT NULL AND p.dst_ip != '')
      AND NOT EXISTS (
          SELECT 1 FROM log_suricata e
          WHERE e.event_date = p.event_date
            AND COALESCE(e.src_ip, '') = COALESCE(p.src_ip, '')
            AND COALESCE(e.dst_ip, '') = COALESCE(p.dst_ip, '')
            AND COALESCE(e.src_port, 0) = COALESCE(p.src_port, 0)
            AND COALESCE(e.dst_port, 0) = COALESCE(p.dst_port, 0)
            AND COALESCE(e.signature, '') = COALESCE(p.signature, '')
      );
    """ % {
        "TMP_SURI_LOG":   TMP_SURI_LOG,
        "DUCKDB_THREADS": DUCKDB_THREADS,
    }

    tmp_sql_fd, tmp_sql_path = tempfile.mkstemp(suffix=".sql")
    try:
        with os.fdopen(tmp_sql_fd, "w") as tmp_sql_file:
            tmp_sql_file.write(SQL_SURICATA)
        with open(tmp_sql_path, "r") as sql_input:
            proc = subprocess.Popen([DUCKDB_BIN, DB_SURICATA], stdin=sql_input, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            _, stderr_out = proc.communicate()
            suri_status = proc.returncode
    finally:
        if os.path.exists(tmp_sql_path):
            os.remove(tmp_sql_path)
    if suri_status != 0:
        log_error("Suricata ingestion error:\n%s" % stderr_out.decode("utf-8", errors="replace"))
if WORKER_SOURCE == "suricata" and not MAINTENANCE_ONLY:
    if suri_status == 0 or suri_size == 0:
        commit_offset(SURI_OFFSET_FILE)
    else:
        log_warning("Suricata offset was not advanced; the delta will be retried.")
    if suri_size == 0:
        suri_status = 0
        log_info("No new Suricata logs to process.")

squid_status = 0 if MAINTENANCE_ONLY and WORKER_SOURCE == "squid" else -1
if squid_size > 0:
    log_info("Importing Squid access log delta (%d bytes) into squid.db..." % squid_size)
    SQL_SQUID = """
    PRAGMA threads=%(DUCKDB_THREADS)s;

    CREATE TABLE IF NOT EXISTS log_squid (
        event_date TIMESTAMP,
        elapsed_ms BIGINT,
        src_ip VARCHAR,
        result VARCHAR,
        http_status INTEGER,
        bytes BIGINT,
        method VARCHAR,
        url VARCHAR,
        username VARCHAR,
        hierarchy VARCHAR,
        destination_ip VARCHAR,
        mime_type VARCHAR,
        http_status_description VARCHAR,
        access_verdict VARCHAR
    );

    ALTER TABLE log_squid ADD COLUMN IF NOT EXISTS http_status_description VARCHAR;
    ALTER TABLE log_squid ADD COLUMN IF NOT EXISTS access_verdict VARCHAR;

    WITH squid_lines AS (
        SELECT string_split(regexp_replace(line, '\\s+', ' ', 'g'), ' ') AS parts
        FROM (
            SELECT unnest(string_split_regex(content, '\\r?\\n')) AS line
            FROM read_text('%(TMP_SQUID_LOG)s')
        )
        WHERE line IS NOT NULL AND line != ''
    ),
    parsed AS (
        SELECT
            date_trunc('second', timezone('America/Sao_Paulo', to_timestamp(TRY_CAST(parts[6] AS DOUBLE)))) AS event_date,
            TRY_CAST(parts[7] AS BIGINT) AS elapsed_ms,
            parts[8] AS src_ip,
            string_split(parts[9], '/')[1] AS result,
            TRY_CAST(string_split(parts[9], '/')[2] AS INTEGER) AS http_status,
            TRY_CAST(parts[10] AS BIGINT) AS bytes,
            parts[11] AS method,
            parts[12] AS url,
            parts[13] AS username,
            string_split(parts[14], '/')[1] AS hierarchy,
            NULLIF(string_split(parts[14], '/')[2], '-') AS destination_ip,
            NULLIF(parts[15], '-') AS mime_type
        FROM squid_lines
        WHERE parts[6] SIMILAR TO '[0-9]+\\.[0-9]+'
          AND position('/' IN parts[9]) > 0
    )
    INSERT INTO log_squid (
        event_date, elapsed_ms, src_ip, result, http_status, bytes,
        method, url, username, hierarchy, destination_ip, mime_type,
        http_status_description, access_verdict
    )
    SELECT DISTINCT
        p.event_date, p.elapsed_ms, p.src_ip, p.result, p.http_status, p.bytes,
        p.method, p.url, p.username, p.hierarchy, p.destination_ip, p.mime_type,
        CASE p.http_status
            WHEN 0 THEN 'No HTTP Response'
            WHEN 100 THEN 'Continue'
            WHEN 101 THEN 'Switching Protocols'
            WHEN 200 THEN 'OK'
            WHEN 201 THEN 'Created'
            WHEN 202 THEN 'Accepted'
            WHEN 203 THEN 'Non-Authoritative Information'
            WHEN 204 THEN 'No Content'
            WHEN 205 THEN 'Reset Content'
            WHEN 206 THEN 'Partial Content'
            WHEN 300 THEN 'Multiple Choices'
            WHEN 301 THEN 'Moved Permanently'
            WHEN 302 THEN 'Found'
            WHEN 303 THEN 'See Other'
            WHEN 304 THEN 'Not Modified'
            WHEN 305 THEN 'Use Proxy'
            WHEN 307 THEN 'Temporary Redirect'
            WHEN 308 THEN 'Permanent Redirect'
            WHEN 400 THEN 'Bad Request'
            WHEN 401 THEN 'Authentication Required'
            WHEN 402 THEN 'Payment Required'
            WHEN 403 THEN 'Access Denied'
            WHEN 404 THEN 'Not Found'
            WHEN 405 THEN 'Method Not Allowed'
            WHEN 406 THEN 'Not Acceptable'
            WHEN 407 THEN 'Proxy Authentication Required'
            WHEN 408 THEN 'Request Timeout'
            WHEN 409 THEN 'Conflict'
            WHEN 410 THEN 'Gone'
            WHEN 411 THEN 'Length Required'
            WHEN 412 THEN 'Precondition Failed'
            WHEN 413 THEN 'Payload Too Large'
            WHEN 414 THEN 'URI Too Long'
            WHEN 415 THEN 'Unsupported Media Type'
            WHEN 416 THEN 'Range Not Satisfiable'
            WHEN 417 THEN 'Expectation Failed'
            WHEN 426 THEN 'Upgrade Required'
            WHEN 428 THEN 'Precondition Required'
            WHEN 429 THEN 'Too Many Requests'
            WHEN 431 THEN 'Request Header Fields Too Large'
            WHEN 500 THEN 'Internal Server Error'
            WHEN 501 THEN 'Not Implemented'
            WHEN 502 THEN 'Bad Gateway'
            WHEN 503 THEN 'Service Unavailable'
            WHEN 504 THEN 'Gateway Timeout'
            WHEN 505 THEN 'HTTP Version Not Supported'
            WHEN 511 THEN 'Network Authentication Required'
            ELSE 'Unknown HTTP Status'
        END AS http_status_description,
        CASE
            WHEN UPPER(p.result) LIKE '%%DENIED%%' OR p.http_status IN (401, 403, 407) THEN 'DENIED'
            WHEN p.http_status = 0 OR p.http_status >= 400 OR UPPER(p.result) LIKE '%%ABORTED%%' THEN 'ERROR'
            ELSE 'ALLOWED'
        END AS access_verdict
    FROM parsed p
    WHERE p.event_date IS NOT NULL
      AND p.src_ip IS NOT NULL AND p.src_ip != ''
      AND p.url IS NOT NULL AND p.url != ''
      AND NOT EXISTS (
          SELECT 1 FROM log_squid e
          WHERE e.event_date = p.event_date
            AND COALESCE(e.src_ip, '') = COALESCE(p.src_ip, '')
            AND COALESCE(e.method, '') = COALESCE(p.method, '')
            AND COALESCE(e.url, '') = COALESCE(p.url, '')
            AND COALESCE(e.bytes, 0) = COALESCE(p.bytes, 0)
      );

    UPDATE log_squid SET event_date = date_trunc('second', event_date)
    WHERE event_date != date_trunc('second', event_date);

    UPDATE log_squid SET http_status_description = CASE http_status
        WHEN 0 THEN 'No HTTP Response' WHEN 100 THEN 'Continue'
        WHEN 101 THEN 'Switching Protocols' WHEN 200 THEN 'OK'
        WHEN 201 THEN 'Created' WHEN 202 THEN 'Accepted'
        WHEN 203 THEN 'Non-Authoritative Information' WHEN 204 THEN 'No Content'
        WHEN 205 THEN 'Reset Content' WHEN 206 THEN 'Partial Content'
        WHEN 300 THEN 'Multiple Choices' WHEN 301 THEN 'Moved Permanently'
        WHEN 302 THEN 'Found' WHEN 303 THEN 'See Other' WHEN 304 THEN 'Not Modified'
        WHEN 305 THEN 'Use Proxy' WHEN 307 THEN 'Temporary Redirect'
        WHEN 308 THEN 'Permanent Redirect' WHEN 400 THEN 'Bad Request'
        WHEN 401 THEN 'Authentication Required' WHEN 402 THEN 'Payment Required'
        WHEN 403 THEN 'Access Denied' WHEN 404 THEN 'Not Found'
        WHEN 405 THEN 'Method Not Allowed' WHEN 406 THEN 'Not Acceptable'
        WHEN 407 THEN 'Proxy Authentication Required' WHEN 408 THEN 'Request Timeout'
        WHEN 409 THEN 'Conflict' WHEN 410 THEN 'Gone' WHEN 411 THEN 'Length Required'
        WHEN 412 THEN 'Precondition Failed' WHEN 413 THEN 'Payload Too Large'
        WHEN 414 THEN 'URI Too Long' WHEN 415 THEN 'Unsupported Media Type'
        WHEN 416 THEN 'Range Not Satisfiable' WHEN 417 THEN 'Expectation Failed'
        WHEN 426 THEN 'Upgrade Required' WHEN 428 THEN 'Precondition Required'
        WHEN 429 THEN 'Too Many Requests' WHEN 431 THEN 'Request Header Fields Too Large'
        WHEN 500 THEN 'Internal Server Error' WHEN 501 THEN 'Not Implemented'
        WHEN 502 THEN 'Bad Gateway' WHEN 503 THEN 'Service Unavailable'
        WHEN 504 THEN 'Gateway Timeout' WHEN 505 THEN 'HTTP Version Not Supported'
        WHEN 511 THEN 'Network Authentication Required' ELSE 'Unknown HTTP Status' END
    WHERE http_status_description IS NULL;

    UPDATE log_squid SET access_verdict = CASE
        WHEN UPPER(result) LIKE '%%DENIED%%' OR http_status IN (401, 403, 407) THEN 'DENIED'
        WHEN http_status = 0 OR http_status >= 400 OR UPPER(result) LIKE '%%ABORTED%%' THEN 'ERROR'
        ELSE 'ALLOWED' END
    WHERE access_verdict IS NULL;
    """ % {
        "TMP_SQUID_LOG": TMP_SQUID_LOG,
        "DUCKDB_THREADS": DUCKDB_THREADS,
    }

    tmp_sql_fd, tmp_sql_path = tempfile.mkstemp(suffix=".sql")
    try:
        with os.fdopen(tmp_sql_fd, "w") as tmp_sql_file:
            tmp_sql_file.write(SQL_SQUID)
        with open(tmp_sql_path, "r") as sql_input:
            proc = subprocess.Popen([DUCKDB_BIN, DB_SQUID], stdin=sql_input, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            _, stderr_out = proc.communicate()
            squid_status = proc.returncode
    finally:
        if os.path.exists(tmp_sql_path):
            os.remove(tmp_sql_path)
    if squid_status != 0:
        log_error("Squid ingestion error:\n%s" % stderr_out.decode("utf-8", errors="replace"))
if WORKER_SOURCE == "squid" and not MAINTENANCE_ONLY:
    if squid_status == 0 or squid_size == 0:
        commit_offset(SQUID_OFFSET_FILE)
    else:
        log_warning("Squid offset was not advanced; the delta will be retried.")
    if squid_size == 0:
        squid_status = 0
        log_info("No new Squid logs to process.")

urlfilter_status = 0 if MAINTENANCE_ONLY and WORKER_SOURCE == "urlfilter" else -1
if urlfilter_size > 0:
    log_info("Importing URL Filter access log delta (%d bytes) into urlfilter.db..." % urlfilter_size)
    SQL_URLFILTER = """
    PRAGMA threads=%(DUCKDB_THREADS)s;

    CREATE TABLE IF NOT EXISTS log_urlfilter (
        event_date TIMESTAMP,
        src_ip VARCHAR,
        username VARCHAR,
        method VARCHAR,
        http_status INTEGER,
        url VARCHAR,
        domain VARCHAR,
        category VARCHAR,
        action_category VARCHAR,
        action VARCHAR
    );

    WITH urlfilter_lines AS (
        SELECT unnest(string_split_regex(content, '\\r?\\n')) AS line
        FROM read_text('%(TMP_URLFILTER_LOG)s')
        WHERE content IS NOT NULL AND content != ''
    ), parsed AS (
        SELECT
            try_strptime('%(CURRENT_YEAR)s ' || substring(line, 1, 15), '%%Y %%b %%d %%H:%%M:%%S') AS event_date,
            regexp_extract(line, ',\\s+([^\\s]+)\\s+.*?\\s+(?:REQMOD|RESPMOD)\\s+', 1) AS src_ip,
            NULLIF(regexp_extract(line, ',\\s+[^\\s]+\\s+(.*?)\\s+(?:REQMOD|RESPMOD)\\s+', 1), '-') AS username,
            regexp_extract(line, '\\s+(REQMOD|RESPMOD)\\s+\\d{3}\\s+', 1) AS method,
            TRY_CAST(regexp_extract(line, '\\s+(?:REQMOD|RESPMOD)\\s+(\\d{3})\\s+', 1) AS INTEGER) AS http_status,
            regexp_extract(line, '\\s+(?:REQMOD|RESPMOD)\\s+\\d{3}\\s+(\\S+)\\s+\\[MatchedCat:', 1) AS url,
            regexp_extract(line, '\\[MatchedCat:\\s*(.*?)\\]', 1) AS category,
            regexp_extract(line, '\\[Action4cat:\\s*(.*?)\\]', 1) AS action_category,
            UPPER(regexp_extract(line, '\\[Action:\\s*([^\\]]+)\\]', 1)) AS action
        FROM urlfilter_lines
        WHERE line LIKE '%%[MatchedCat:%%' AND line LIKE '%%[Action:%%'
    )
    INSERT INTO log_urlfilter (
        event_date, src_ip, username, method, http_status, url, domain,
        category, action_category, action
    )
    SELECT
        event_date, src_ip, COALESCE(NULLIF(username, ''), 'Unauthenticated'), method,
        http_status, url,
        LOWER(regexp_extract(url, '^(?:https?://)?([^/:]+)', 1)) AS domain,
        COALESCE(NULLIF(category, ''), 'Unclassified'), action_category, action
    FROM parsed
    WHERE event_date IS NOT NULL
      AND src_ip IS NOT NULL AND src_ip != ''
      AND url IS NOT NULL AND url != ''
      AND action IS NOT NULL AND action != '';
    """ % {
        "TMP_URLFILTER_LOG": TMP_URLFILTER_LOG,
        "CURRENT_YEAR": CURRENT_YEAR,
        "DUCKDB_THREADS": DUCKDB_THREADS,
    }

    tmp_sql_fd, tmp_sql_path = tempfile.mkstemp(suffix=".sql")
    try:
        with os.fdopen(tmp_sql_fd, "w") as tmp_sql_file:
            tmp_sql_file.write(SQL_URLFILTER)
        with open(tmp_sql_path, "r") as sql_input:
            proc = subprocess.Popen([DUCKDB_BIN, DB_URLFILTER], stdin=sql_input, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            _, stderr_out = proc.communicate()
            urlfilter_status = proc.returncode
    finally:
        if os.path.exists(tmp_sql_path):
            os.remove(tmp_sql_path)
    if urlfilter_status != 0:
        log_error("URL Filter ingestion error:\n%s" % stderr_out.decode("utf-8", errors="replace"))
if WORKER_SOURCE == "urlfilter" and not MAINTENANCE_ONLY:
    if urlfilter_status == 0 or urlfilter_size == 0:
        commit_offset(URLFILTER_OFFSET_FILE)
    else:
        log_warning("URL Filter offset was not advanced; the delta will be retried.")
    if urlfilter_size == 0:
        urlfilter_status = 0
        log_info("No new URL Filter logs to process.")

# Clean up only this worker's delta; workers for other sources run concurrently.
current_tmp = {
    "firewall": TMP_LOG,
    "messages": TMP_MSG_LOG,
    "suricata": TMP_SURI_LOG,
    "squid": TMP_SQUID_LOG,
    "urlfilter": TMP_URLFILTER_LOG,
}[WORKER_SOURCE]
if not MAINTENANCE_ONLY and os.path.exists(current_tmp):
    os.remove(current_tmp)

# ============================================================
# GEOIP ENRICHMENT
# ============================================================
def run_geoip_enrichment(db_path, table_name):
    log_info("Checking GeoIP cache status in %s..." % os.path.basename(db_path))
    must_reload = True
    try:
        proc_chk = subprocess.Popen([DUCKDB_BIN, "-readonly", db_path, "SELECT version FROM geoip_metadata;"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout_chk, _ = proc_chk.communicate()
        if GEOIP_VERSION_TAG in stdout_chk.decode('utf-8'):
            proc_cnt = subprocess.Popen([DUCKDB_BIN, "-readonly", db_path, "SELECT COUNT(*) FROM geoip_cache;"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            stdout_cnt, _ = proc_cnt.communicate()
            if b"0" not in stdout_cnt:
                must_reload = False
    except Exception:
        pass

    SQL_GEOIP = "PRAGMA threads=%d;\n" % GEOIP_THREADS
    SQL_GEOIP += "CREATE TABLE IF NOT EXISTS geoip_metadata (version VARCHAR);\n"
    SQL_GEOIP += "CREATE TABLE IF NOT EXISTS geoip_cache (ip_start BIGINT, ip_end BIGINT, country_code VARCHAR, country_name VARCHAR);\n"
    SQL_GEOIP += "UPDATE %(TABLE)s SET src_country_code = 'PENDING', src_country_name = 'Processing...' WHERE src_country_code = 'LAN' AND src_ip NOT SIMILAR TO '(10\\..*|192\\.168\\..*|172\\.(1[6-9]|2[0-9]|3[0-1])\\..*|127\\..*)';\n" % {"TABLE": table_name}
    SQL_GEOIP += "UPDATE %(TABLE)s SET dst_country_code = 'PENDING', dst_country_name = 'Processing...' WHERE dst_country_code = 'LAN' AND dst_ip NOT SIMILAR TO '(10\\..*|192\\.168\\..*|172\\.(1[6-9]|2[0-9]|3[0-1])\\..*|127\\..*)';\n" % {"TABLE": table_name}

    if must_reload:
        log_warning("Loading and indexing MaxMind GeoIP CSVs in %s..." % os.path.basename(db_path))
        SQL_GEOIP += "DROP TABLE IF EXISTS geoip_cache;\n"
        SQL_GEOIP += """
        CREATE TABLE geoip_cache AS 
        SELECT
            ( Prague.ip_parts[1]::BIGINT << 24 ) + ( Prague.ip_parts[2]::BIGINT << 16 ) + ( Prague.ip_parts[3]::BIGINT << 8 ) + Prague.ip_parts[4]::BIGINT AS ip_start,
            (( Prague.ip_parts[1]::BIGINT << 24 ) + ( Prague.ip_parts[2]::BIGINT << 16 ) + ( Prague.ip_parts[3]::BIGINT << 8 ) + Prague.ip_parts[4]::BIGINT) + (power(2, 32 - Prague.mask) - 1)::BIGINT AS ip_end,
            loc.country_iso_code AS country_code,
            loc.country_name     AS country_name
        FROM (
            SELECT 
                string_to_array(string_split(network, '/')[1], '.') AS ip_parts,
                string_split(network, '/')[2]::INTEGER AS mask,
                registered_country_geoname_id,
                geoname_id
            FROM read_csv('%(GEOIP_BLOCKS_V4)s', AUTO_DETECT=TRUE)
        ) AS Prague
        JOIN read_csv('%(GEOIP_LOCATIONS)s', AUTO_DETECT=TRUE) AS loc
          ON COALESCE(NULLIF(Prague.geoname_id::VARCHAR, ''), Prague.registered_country_geoname_id::VARCHAR) = loc.geoname_id::VARCHAR
        WHERE loc.country_iso_code IS NOT NULL AND loc.country_iso_code != ''
        ORDER BY ip_start, ip_end;\n""" % {"GEOIP_BLOCKS_V4": GEOIP_BLOCKS_V4, "GEOIP_LOCATIONS": GEOIP_LOCATIONS}
        SQL_GEOIP += "DELETE FROM geoip_metadata; INSERT INTO geoip_metadata VALUES ('%s');\n" % GEOIP_VERSION_TAG
    else:
        log_info("GeoIP cache is up to date in %s." % os.path.basename(db_path))

    log_info("Running fast IP lookup match (BIGINT) in %s..." % os.path.basename(db_path))
    SQL_GEOIP += """
    CREATE OR REPLACE TEMP TABLE pending_ips AS
    SELECT DISTINCT ip,
        (parts[1]::BIGINT << 24) + (parts[2]::BIGINT << 16) + (parts[3]::BIGINT << 8) + parts[4]::BIGINT AS ip_num
    FROM (
        SELECT ip, string_to_array(ip, '.') AS parts
        FROM (
            SELECT src_ip AS ip FROM %(TABLE)s WHERE src_country_code = 'PENDING'
            UNION
            SELECT dst_ip AS ip FROM %(TABLE)s WHERE dst_country_code = 'PENDING'
        )
        WHERE ip SIMILAR TO '[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+'
    ) AS parsed;

    CREATE OR REPLACE TEMP TABLE resolved_ips AS
    SELECT ip, country_code, country_name FROM (
        SELECT p.ip, geo.country_code, geo.country_name,
               ROW_NUMBER() OVER (PARTITION BY p.ip ORDER BY (geo.ip_end - geo.ip_start) ASC) AS rn
        FROM pending_ips AS p
        JOIN geoip_cache AS geo ON p.ip_num >= geo.ip_start AND p.ip_num <= geo.ip_end
    ) WHERE rn = 1;

    UPDATE %(TABLE)s AS target SET src_country_code = r.country_code, src_country_name = r.country_name FROM resolved_ips AS r WHERE target.src_country_code = 'PENDING' AND target.src_ip = r.ip;
    UPDATE %(TABLE)s AS target SET dst_country_code = r.country_code, dst_country_name = r.country_name FROM resolved_ips AS r WHERE target.dst_country_code = 'PENDING' AND target.dst_ip = r.ip;
    
    UPDATE %(TABLE)s SET src_country_code = 'LAN', src_country_name = 'Local Network' WHERE src_country_code = 'PENDING' AND src_ip IS NOT NULL AND src_ip != '';
    UPDATE %(TABLE)s SET dst_country_code = 'LAN', dst_country_name = 'Local Network' WHERE dst_country_code = 'PENDING' AND dst_ip IS NOT NULL AND dst_ip != '';
    
    UPDATE %(TABLE)s SET src_country_code = 'UNKNOWN', src_country_name = 'Unknown' WHERE src_country_code = 'PENDING';
    UPDATE %(TABLE)s SET dst_country_code = 'UNKNOWN', dst_country_name = 'Unknown' WHERE dst_country_code = 'PENDING';
    """ % {"TABLE": table_name}

    tmp_geo_fd, tmp_geo_path = tempfile.mkstemp(suffix=".sql")
    try:
        with os.fdopen(tmp_geo_fd, "w") as tmp_geo_file:
            tmp_geo_file.write(SQL_GEOIP)
        with open(tmp_geo_path, "r") as geo_input:
            proc_geo = subprocess.Popen([DUCKDB_BIN, db_path], stdin=geo_input, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            _, stderr_geo = proc_geo.communicate()
            geo_status = proc_geo.returncode
    finally:
        if os.path.exists(tmp_geo_path):
            os.remove(tmp_geo_path)

    if geo_status != 0:
        log_error("GeoIP enrichment error in %s:\n%s" % (os.path.basename(db_path), stderr_geo.decode("utf-8", errors="replace")))
    else:
        log_info("IP Geolocation enrichment completed successfully for %s." % os.path.basename(db_path))

# Enrich after every successful ingestion cycle (60 seconds), not only during
# the 300-second retention cycle. The per-source lock serializes DB writers.
if GEOIP_CSV_DIR:
    if WORKER_SOURCE == "firewall" and fw_status == 0:
        run_geoip_enrichment(DB_FIREWALL, "log_firewall")
    if WORKER_SOURCE == "suricata" and suri_status == 0:
        run_geoip_enrichment(DB_SURICATA, "log_suricata")

# ============================================================
# RETENTION CLEANUP
# ============================================================
if MAINTENANCE_ONLY:
    log_info("Executing data retention cleanup policy...")
keep_days = get_log2db_keep_days()
if MAINTENANCE_ONLY:
    log_info("Applied LOG2DB_KEEP_HISTORY retention threshold: %d days" % keep_days)

if MAINTENANCE_ONLY and fw_status == 0 and os.path.exists(DB_FIREWALL):
    p_clean = subprocess.Popen([DUCKDB_BIN, DB_FIREWALL], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    sql_clean_fw = ("PRAGMA threads=%%d; DELETE FROM log_firewall WHERE event_date < CURRENT_DATE - INTERVAL %d DAY;" % keep_days) % DUCKDB_THREADS
    p_clean.communicate(input=sql_clean_fw.encode("utf-8"))

if MAINTENANCE_ONLY and msg_status == 0 and os.path.exists(DB_MESSAGES):
    p_clean = subprocess.Popen([DUCKDB_BIN, DB_MESSAGES], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    sql_clean_msg = ("PRAGMA threads=%%d; DELETE FROM log_messages WHERE event_date < CURRENT_DATE - INTERVAL %d DAY;" % keep_days) % DUCKDB_THREADS
    p_clean.communicate(input=sql_clean_msg.encode("utf-8"))

if MAINTENANCE_ONLY and suri_status == 0 and os.path.exists(DB_SURICATA):
    p_clean = subprocess.Popen([DUCKDB_BIN, DB_SURICATA], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    sql_clean_suri = ("PRAGMA threads=%%d; DELETE FROM log_suricata WHERE event_date < CURRENT_DATE - INTERVAL %d DAY;" % keep_days) % DUCKDB_THREADS
    p_clean.communicate(input=sql_clean_suri.encode("utf-8"))

if MAINTENANCE_ONLY and squid_status == 0 and os.path.exists(DB_SQUID):
    p_clean = subprocess.Popen([DUCKDB_BIN, DB_SQUID], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    sql_clean_squid = ("PRAGMA threads=%%d; DELETE FROM log_squid WHERE event_date < CURRENT_DATE - INTERVAL %d DAY;" % keep_days) % DUCKDB_THREADS
    p_clean.communicate(input=sql_clean_squid.encode("utf-8"))

if MAINTENANCE_ONLY and urlfilter_status == 0 and os.path.exists(DB_URLFILTER):
    p_clean = subprocess.Popen([DUCKDB_BIN, DB_URLFILTER], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    sql_clean_urlfilter = ("PRAGMA threads=%%d; DELETE FROM log_urlfilter WHERE event_date < CURRENT_DATE - INTERVAL %d DAY;" % keep_days) % DUCKDB_THREADS
    p_clean.communicate(input=sql_clean_urlfilter.encode("utf-8"))

# ============================================================
# PERMISSIONS
# ============================================================
import grp
import pwd
for db_f in (DB_FIREWALL, DB_MESSAGES, DB_SURICATA, DB_SQUID, DB_URLFILTER):
    if os.path.exists(db_f):
        try:
            uid = pwd.getpwnam("root").pw_uid
            gid = grp.getgrnam("nogroup").gr_gid
            os.chown(db_f, uid, gid)
        except KeyError:
            pass
        os.chmod(db_f, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IWGRP | stat.S_IROTH)

release_lock()

end_time = time.time()
worker_status = {
    "firewall": fw_status,
    "messages": msg_status,
    "suricata": suri_status,
    "squid": squid_status,
    "urlfilter": urlfilter_status,
}[WORKER_SOURCE]
if worker_status != 0:
    log_error("%s %s failed after %.2f seconds; uncommitted data will be retried." % (
        WORKER_SOURCE.capitalize(), "maintenance" if MAINTENANCE_ONLY else "ingestion",
        end_time - start_time))
    sys.exit(1)

log_info("%s %s completed successfully in %.2f seconds!" % (
    WORKER_SOURCE.capitalize(), "maintenance" if MAINTENANCE_ONLY else "ingestion",
    end_time - start_time))