#!/bin/bash
# =============================================================================
# ISE Session Monitoring Script - Home Lab
# =============================================================================
# Purpose: Check active ISE sessions and authentication status
# Usage: ./ise-session-check.sh [MAC_ADDRESS]
# Requires: netapi CLI tool (pip install netapi)

set -euo pipefail

# tag::vars[]
# Environment variables (override with environment)
ISE_PAN_IP="${ISE_PAN_IP:-10.50.1.21}"
ISE_API_USER="${ISE_API_USER:-domus_ers_admin}"
ISE_API_PASS="${ISE_API_PASS:-}"  # Load from dsec or environment
MAC_ADDRESS="${1:-}"

# Colors for output
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# end::vars[]

# tag::validation[]
# Validate inputs
if [ -z "$MAC_ADDRESS" ]; then
    echo "Usage: $0 <MAC_ADDRESS>"
    echo "Example: $0 b4:e9:b8:f6:c8:17"
    exit 1
fi

if [ -z "$ISE_API_PASS" ]; then
    echo -e "${RED}Error: ISE_API_PASS not set${NC}"
    echo "Load credentials: dsource d000 dev/network"
    exit 1
fi
# end::validation[]

# tag::banner[]
echo "========================================"
echo "ISE Session Monitor - Home Lab"
echo "========================================"
echo "ISE PAN: $ISE_PAN_IP"
echo "Device: $MAC_ADDRESS"
echo "========================================"
echo ""
# end::banner[]

# tag::session-query[]
# Check active session
echo -e "${YELLOW}→ Checking active session...${NC}"
if netapi ise mnt session "$MAC_ADDRESS" 2>/dev/null; then
    echo -e "${GREEN}✓ Session found${NC}"
else
    echo -e "${RED}✗ No active session${NC}"
fi
echo ""
# end::session-query[]

# tag::auth-status[]
# Check authentication status
echo -e "${YELLOW}→ Checking authentication status...${NC}"
if netapi ise mnt auth-status "$MAC_ADDRESS" 2>/dev/null; then
    echo -e "${GREEN}✓ Authentication successful${NC}"
else
    echo -e "${RED}✗ Authentication failed or not found${NC}"
fi
echo ""
# end::auth-status[]

# tag::endpoint-info[]
# Get endpoint details
echo -e "${YELLOW}→ Checking endpoint registration...${NC}"
if netapi ise get-endpoint "$MAC_ADDRESS" 2>/dev/null; then
    echo -e "${GREEN}✓ Endpoint registered${NC}"
else
    echo -e "${RED}✗ Endpoint not registered${NC}"
fi
echo ""
# end::endpoint-info[]

# tag::recent-auth[]
# Check recent authentication history
echo -e "${YELLOW}→ Recent authentication attempts (last 10)...${NC}"
netapi ise dc auth-history "$MAC_ADDRESS" --limit 10 2>/dev/null || \
    echo -e "${RED}✗ DataConnect not available${NC}"
echo ""
# end::recent-auth[]

echo "========================================"
echo "Monitoring complete"
echo "========================================"
