#!/bin/sh /etc/rc.common
# Gateway log capture init script for filtered gateway logging
# Logs ERR/WARN messages for gw400, btb600, and cloud-comm to /var/log/gateway.log (RAM)
# Rotated hourly to SD card by logrotate to /data/gateway-log

START=13
STOP=10

USE_PROCD=1

LOG_FILE="/var/log/gateway.log"
ROTATE_DIR="/data/gateway-log"
FILTER_REGEX="(\.(err|warn) (app1|app2|cloud-comm)[^:]*:)|(cloud-comm[^:]*:.*(\[ERROR\]|\[WARN\]))|((bg95-watchdog):)"

start_service() {
    echo "Starting gateway log capture..."

    # Ensure log file exists
    [ -f "$LOG_FILE" ] || { touch "$LOG_FILE" && chmod 640 "$LOG_FILE"; }
    # Ensure rotation directory exists
    [ -d "$ROTATE_DIR" ] || { mkdir -p "$ROTATE_DIR" && chmod 750 "$ROTATE_DIR"; }
    # Ensure /var/lib/ exists for default logrotate state file
    [ -d "/var/lib/" ] || { mkdir -p "/var/lib/" && chmod 755 "/var/lib/"; }

    procd_open_instance
    procd_set_param command /usr/bin/gateway-log "$LOG_FILE" "$FILTER_REGEX"
    procd_set_param respawn 3600 5 0
    procd_set_param stdout 0
    procd_set_param stderr 1
    procd_close_instance
}

stop_service() {
    echo "Stopping gateway log capture..."
}
