#!/bin/bash
# rdev logs - Easy log viewing for rdev-api
# Usage: ./scripts/logs.sh [options]
#
# Options:
#   -f, --follow     Stream logs (like tail -f)
#   -n, --lines NUM  Number of lines (default: 100)
#   -e, --errors     Only show errors/warnings
#   -a, --all        Show all pods (including previous crashes)
#   -p, --previous   Show logs from previous container instance
#   -h, --help       Show this help

set -euo pipefail

export KUBECONFIG="${KUBECONFIG:-$HOME/.kube/orchard9-k3sf.yaml}"

FOLLOW=""
LINES="100"
ERRORS_ONLY=""
ALL_PODS=""
PREVIOUS=""

while [[ $# -gt 0 ]]; do
    case $1 in
        -f|--follow)
            FOLLOW="-f"
            shift
            ;;
        -n|--lines)
            LINES="$2"
            shift 2
            ;;
        -e|--errors)
            ERRORS_ONLY="1"
            shift
            ;;
        -a|--all)
            ALL_PODS="1"
            shift
            ;;
        -p|--previous)
            PREVIOUS="--previous"
            shift
            ;;
        -h|--help)
            head -14 "$0" | tail -13
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            exit 1
            ;;
    esac
done

if [[ -n "$ALL_PODS" ]]; then
    # Show logs from all rdev-api pods
    kubectl logs -n rdev -l app=rdev-api --tail="$LINES" $FOLLOW $PREVIOUS
elif [[ -n "$ERRORS_ONLY" ]]; then
    # Filter for errors/warnings only
    kubectl logs -n rdev -l app=rdev-api --tail="$LINES" $PREVIOUS | grep -iE "error|warn|fatal|panic"
else
    # Default: latest pod logs
    kubectl logs -n rdev -l app=rdev-api --tail="$LINES" $FOLLOW $PREVIOUS
fi
