#!/bin/sh
set -e

LOGDIR=/usr/local/nginx/logs
ASAN_DIR=/tmp
mkdir -p "$LOGDIR"

# Make sure the unprivileged worker user ('nobody') can write the nginx logs
# dir (error.log/pid are owned by the master, but keep this writable as a
# belt-and-suspenders so no ASan path ever hits EACCES).
chown -R nobody:nogroup "$LOGDIR" 2>/dev/null || true
chmod 0777 "$LOGDIR" 2>/dev/null || true

# /tmp is world-writable (1777) in the base image; the worker can always write
# its ASan report here regardless of the user it drops to. This is the FIX for
# the prior run's lost backtrace (worker as 'nobody' could not write the
# root-owned logs dir, ASan got EACCES, and aborted WITHOUT dumping the report
# to ANY channel).
chmod 1777 "$ASAN_DIR" 2>/dev/null || true

# Clean baseline: clear the error log and any ASan reports from a prior run so
# the verifier's post-restart state is pristine and the crash report is
# unambiguously attributable to the candidate exploit.
: > "$LOGDIR/error.log"
rm -f "$LOGDIR"/asan.log* "$ASAN_DIR"/asan.log* 2>/dev/null || true

# AddressSanitizer configuration:
#  - log_path=/tmp/asan.log -> each process writes logs/asan.log.<pid>; the
#    worker (as 'nobody') can ALWAYS write here -> heap-buffer-overflow report
#    is captured server-side with a backtrace naming the vulnerable frame.
#  - abort_on_error=1 -> ASan raises SIGABRT after dumping its report, so the
#    worker dies with a memory-fault signal the master records in error.log.
#  - detect_leaks=0 -> nginx pools "leak" by design; suppress exit noise.
#  - log_exe_name=1 -> include the executable name in the report filename hint.
export ASAN_OPTIONS="log_path=$ASAN_DIR/asan.log:abort_on_error=1:detect_leaks=0:disable_coredump=0:handle_abort=1:print_stats=0:symbolize=1"
# Help ASan find a symbolizer if one is installed.
export ASAN_SYMBOLIZER_PATH="$(command -v llvm-symbolizer || command -v addr2line || true)"

echo "[entrypoint] nginx version:"
cat /usr/local/nginx/nginx-version.txt 2>/dev/null || true
echo "[entrypoint] nginx commit: $(cat /usr/local/nginx/nginx-commit.txt 2>/dev/null)"
echo "[entrypoint] ASAN_OPTIONS=$ASAN_OPTIONS"

# Validate the config before launch (fails fast on a broken build).
/usr/local/nginx/sbin/nginx -t

# Stream the error log to container stdout for convenience; the file itself
# (logs/error.log + /tmp/asan.log.*) remains the authoritative crash channel.
tail -n0 -F "$LOGDIR/error.log" &

# Run nginx in the foreground as the container's main process.
# 'daemon off;' is already set in nginx.conf, so do not duplicate it here.
exec /usr/local/nginx/sbin/nginx
