#!/bin/sh
#
# mars_packtest.sh v3
#
# Collect a MARS NWE DOS test ZIP, append recent nw.log lines,
# copy final package to /tmp, and fix ownership/permissions.
#
# Usage:
#   mars_packtest.sh <testname> [minutes] [upload_user]
#
# Example:
#   sudo ./mars_packtest.sh ncptsta 5 mario
#

set -eu

TEST_IN="${1:-}"
MINUTES="${2:-5}"
UPLOAD_USER="${3:-${SUDO_USER:-$(id -un)}}"

LOG_FILE="/var/log/mars_nwe/nw.log"
SYS_DIR="/var/mars_nwe/SYS"
OUT_DIR="/tmp"

if [ -z "$TEST_IN" ]; then
  echo "Usage: $0 <testname> [minutes] [upload_user]" >&2
  exit 2
fi

TEST="$(printf '%s' "$TEST_IN" | tr '[:lower:]' '[:upper:]')"

TEST_DIR="$TEST"
ZIP_NAME="$TEST.ZIP"

case "$TEST" in
  NCPTSTA)
    TEST_DIR="NCMP"
    ZIP_NAME="NCPTSTA.ZIP"
    ;;
  FILTSTN|FILPREN|FILPOSTN|FILCMPN)
    TEST_DIR="TFILE"
    ZIP_NAME="$TEST.ZIP"
    ;;
  NDIRTSTN|NDIRTSTM|NDIRCMP)
    TEST_DIR="TNDIR"
    ZIP_NAME="$TEST.ZIP"
    ;;
esac

SRC_ZIP="$SYS_DIR/$TEST_DIR/$ZIP_NAME"

if [ ! -f "$SRC_ZIP" ]; then
  FOUND="$(find "$SYS_DIR" -maxdepth 3 -type f -iname "$TEST.zip" -print 2>/dev/null | head -n 1 || true)"
  if [ -n "$FOUND" ]; then
    SRC_ZIP="$FOUND"
    ZIP_NAME="$(basename "$SRC_ZIP")"
  fi
fi

if [ ! -f "$SRC_ZIP" ]; then
  echo "ERROR: ZIP not found for test '$TEST_IN'." >&2
  echo "Tried: $SRC_ZIP" >&2
  echo "Also searched: $SYS_DIR -maxdepth 3 -iname $TEST.zip" >&2
  exit 1
fi

if [ ! -f "$LOG_FILE" ]; then
  echo "ERROR: log file not found: $LOG_FILE" >&2
  exit 1
fi

STAMP="$(date '+%Y%m%d-%H%M%S')"
WORK="/tmp/mars_packtest_${TEST}_$$"
FINAL="$OUT_DIR/${TEST}_${STAMP}_with_log.zip"
LOG_OUT="$WORK/nw_last_${MINUTES}min.log"
INFO_OUT="$WORK/package_info.txt"

mkdir -p "$WORK"

# Copy original ZIP first, so the original test result remains untouched.
cp "$SRC_ZIP" "$FINAL"

NOW_EPOCH="$(date '+%s')"
FROM_EPOCH="$((NOW_EPOCH - MINUTES * 60))"

# Compute comparable keys outside awk. This avoids running date(1) once per
# log line, which is very slow for large nw.log files.
#
# Key format:
#   MMDD * 86400 + seconds_since_midnight
#
# This is intended for short windows like 5-60 minutes. It also handles
# midnight wrap for the normal "last few minutes" case.
FROM_MD="$(date -d "@$FROM_EPOCH" '+%m%d')"
FROM_SOD="$(date -d "@$FROM_EPOCH" '+%H:%M:%S' | awk -F: '{print ($1*3600)+($2*60)+$3}')"
NOW_MD="$(date -d "@$NOW_EPOCH" '+%m%d')"
NOW_SOD="$(date -d "@$NOW_EPOCH" '+%H:%M:%S' | awk -F: '{print ($1*3600)+($2*60)+$3}')"

FROM_KEY="$((10#$FROM_MD * 86400 + FROM_SOD))"
NOW_KEY="$((10#$NOW_MD * 86400 + NOW_SOD))"

# Force byte/C locale. nw.log can contain CP437/Latin-1/debug bytes.
LC_ALL=C awk -v from_key="$FROM_KEY" -v now_key="$NOW_KEY" '
{
  # Log timestamp format:
  #   05.26,10:52:36 ...
  if (match($0, /^[0-9][0-9]\.[0-9][0-9],[0-9][0-9]:[0-9][0-9]:[0-9][0-9]/)) {
    mon = substr($0, 1, 2) + 0
    day = substr($0, 4, 2) + 0
    hh  = substr($0, 7, 2) + 0
    mm  = substr($0, 10, 2) + 0
    ss  = substr($0, 13, 2) + 0
    key = ((mon * 100) + day) * 86400 + (hh * 3600) + (mm * 60) + ss

    if (from_key <= now_key) {
      if (key >= from_key && key <= now_key) print
    } else {
      # Midnight/month/year wrap for short recent windows.
      if (key >= from_key || key <= now_key) print
    }
  }
}
' "$LOG_FILE" > "$LOG_OUT"

{
  echo "MARS NWE test package"
  echo "====================="
  echo
  echo "Test input:     $TEST_IN"
  echo "Test name:      $TEST"
  echo "Source ZIP:     $SRC_ZIP"
  echo "Final ZIP:      $FINAL"
  echo "Log file:       $LOG_FILE"
  echo "Log window:     last $MINUTES minute(s)"
  echo "Created:        $(date)"
  echo "Upload user:    $UPLOAD_USER"
  echo "From key:       $FROM_KEY"
  echo "Now key:        $NOW_KEY"
  echo
  echo "Included extra files:"
  echo "  nw_last_${MINUTES}min.log"
  echo "  package_info.txt"
} > "$INFO_OUT"

(
  cd "$WORK"
  zip -q "$FINAL" "$(basename "$LOG_OUT")" "$(basename "$INFO_OUT")"
)

if id "$UPLOAD_USER" >/dev/null 2>&1; then
  chown "$UPLOAD_USER":"$(id -gn "$UPLOAD_USER")" "$FINAL" || true
fi
chmod 0644 "$FINAL"

rm -rf "$WORK"

echo "Created package:"
echo "  $FINAL"
echo
echo "Upload as user:"
echo "  $UPLOAD_USER"
