#!/bin/bash

# 🔐 Ensure running as root
if [[ "$EUID" -ne 0 ]]; then
  echo "❌ Please run as root (use sudo)."
  exit 1
fi

LOGFILE="/var/log/caddy/reverse_proxy.log"

HOST_FILTER=""
STATUS_FILTER=""
URI_FILTER=""
METHOD_FILTER=""

# Parse command-line arguments
while [[ $# -gt 0 ]]; do
  case "$1" in
    --host)
      HOST_FILTER="$2"
      shift 2
      ;;
    --status)
      STATUS_FILTER="$2"
      shift 2
      ;;
    --uri)
      URI_FILTER="$2"
      shift 2
      ;;
    --method)
      METHOD_FILTER="$2"
      shift 2
      ;;
    *)
      echo "❌ Unknown argument: $1"
      echo "Usage: $0 [--host HOST] [--status CODE] [--uri KEYWORD] [--method METHOD]"
      exit 1
      ;;
  esac
done

tail -f "$LOGFILE" | jq -r --arg host "$HOST_FILTER" --arg status "$STATUS_FILTER" --arg uri "$URI_FILTER" --arg method "$METHOD_FILTER" '
  select(.logger == "http.handlers.reverse_proxy") |

  select(($host == "" or .request.host == $host) and
         ($status == "" or (.status | tostring) == $status) and
         ($uri == "" or (.request.uri | test($uri))) and
         ($method == "" or (.request.method | ascii_downcase) == ($method | ascii_downcase))) |

  "\u001b[34m\(.ts | todate)\u001b[0m " +
  "\u001b[35m\(.request.host // "-")\u001b[0m " +
  "\u001b[33m\(.request.uri // "-")\u001b[0m " +
  (if .status >= 500 then "\u001b[31m[\(.status)]" elif .status >= 400 then "\u001b[33m[\(.status)]" else "\u001b[32m[\(.status)]" end) +
  " \u001b[36m\(.request.method)\u001b[0m " +
  (if .level == "info" then "\u001b[32mINFO" elif .level == "warn" then "\u001b[33mWARN" elif .level == "error" then "\u001b[31mERROR" else "\u001b[36m\(.level|ascii_upcase)" end) +
  "\u001b[0m \u001b[1m\(.msg)\u001b[0m"
'