#!/bin/bash
# ppf-logs -- view PPF container logs
#
# Usage:
#   ppf-logs [options] [node]
#
# Defaults to odin if no node specified.

set -eu

# Resolve to real path (handles symlinks from ~/.local/bin/)
SCRIPT_PATH="$(cd "$(dirname "$0")" && pwd)/$(basename "$0")"
SCRIPT_DIR="$(dirname "$(readlink -f "$SCRIPT_PATH")")"
# shellcheck disable=SC1091
. "$SCRIPT_DIR/lib/ppf-common.sh"

# ---------------------------------------------------------------------------
# Usage
# ---------------------------------------------------------------------------
usage() {
    cat <<EOF
Usage: ppf-logs [options] [node]

View PPF container logs.

Nodes:
  odin, cassius, edge, sentinel (default: odin)

Options:
  -f             follow log output
  -n LINES       number of lines to show (default: 40)
  --help         show this help
  --version      show version

Examples:
  ppf-logs                  last 40 lines from odin
  ppf-logs cassius          last 40 lines from cassius
  ppf-logs -f edge          follow edge worker logs
  ppf-logs -n 100 sentinel  last 100 lines from sentinel
EOF
    exit 0
}

# ---------------------------------------------------------------------------
# Parse args
# ---------------------------------------------------------------------------
FOLLOW=0
LINES=40
NODE=""

while [ $# -gt 0 ]; do
    case "$1" in
        --help|-h)    usage ;;
        --version|-V) echo "ppf-logs $PPF_TOOLS_VERSION"; exit 0 ;;
        -f)           FOLLOW=1 ;;
        -n)           shift; LINES="${1:?'-n' requires a number}" ;;
        -*)           die "Unknown option: $1" ;;
        *)            NODE="$1" ;;
    esac
    shift
done

NODE="${NODE:-$MASTER}"

# Validate node
is_master "$NODE" || is_worker "$NODE" || die "Unknown node: $NODE"

CNAME=$(container_name "$NODE")

# ---------------------------------------------------------------------------
# Build podman logs command
# ---------------------------------------------------------------------------
CMD="podman logs --tail $LINES"
[ "$FOLLOW" -eq 1 ] && CMD="$CMD -f"
CMD="$CMD $CNAME"

section "$NODE ($CNAME)"

# Run with raw output -- logs go straight to terminal
podman_cmd "$NODE" "$CMD"
