#!/usr/bin/bash
#
# ai-read-log -- Read a log file from /var/log/ with path validation.
# Used by the BlueOnyx AI agent via sudo to read system logs as root.
#
set -e

PATH=/bin:/usr/bin:/usr/local/bin

# --- Help / usage -----------------------------------------------------------
usage() {
    echo "Usage: $(basename "$0") <abs-path-under-/var/log/>" >&2
    exit 1
}

# --- Argument validation ----------------------------------------------------
if [ $# -ne 1 ]; then
    echo "ERROR: Exactly one argument required (file path)." >&2
    usage
fi

FILE="$1"

# Must be an absolute path
if [ "${FILE:0:1}" != "/" ]; then
    echo "ERROR: Path must be absolute: $FILE" >&2
    exit 1
fi

# Resolve symlinks
RESOLVED="$(readlink -f "$FILE" 2>/dev/null)" || {
    echo "ERROR: Cannot resolve path: $FILE" >&2
    exit 1
}

# Must start with /var/log/
case "$RESOLVED" in
    /var/log/*)
        ;;
    *)
        echo "ERROR: Path resolves outside /var/log/: $FILE -> $RESOLVED" >&2
        exit 1
        ;;
esac

# Must exist and be a regular file
if [ ! -f "$RESOLVED" ]; then
    echo "ERROR: Not a regular file or does not exist: $RESOLVED" >&2
    exit 1
fi

# --- Output ----------------------------------------------------------------
cat "$RESOLVED"
exit 0

# 
# Copyright (c) 2008-2026 Michael Stauber, SOLARSPEED.NET
# Copyright (c) 2008-2026 Team BlueOnyx, BLUEONYX.IT
# All Rights Reserved.
# 
# 1. Redistributions of source code must retain the above copyright 
#    notice, this list of conditions and the following disclaimer.
# 
# 2. Redistributions in binary form must reproduce the above copyright 
#    notice, this list of conditions and the following disclaimer in 
#    the documentation and/or other materials provided with the 
#    distribution.
# 
# 3. Neither the name of the copyright holder nor the names of its 
#    contributors may be used to endorse or promote products derived 
#    from this software without specific prior written permission.
# 
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
# POSSIBILITY OF SUCH DAMAGE.
# 
# You acknowledge that this software is not designed or intended for 
# use in the design, construction, operation or maintenance of any 
# nuclear facility.
# 
