#!/bin/sh

#
# SecuBox Diagnostics System
# Health checks and diagnostic reporting
#

. /usr/share/libubox/jshn.sh
. /lib/functions.sh

# Color output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# Health check thresholds
CPU_THRESHOLD=$(uci -q get secubox.settings.health_threshold_cpu || echo "80")
MEM_THRESHOLD=$(uci -q get secubox.settings.health_threshold_memory || echo "90")
STORAGE_THRESHOLD=$(uci -q get secubox.settings.health_threshold_storage || echo "85")

# Run comprehensive health check
health_check() {
	echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
	echo -e "${BLUE}SecuBox System Health Check${NC}"
	echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
	echo ""

	local overall_status="healthy"
	local warnings=0
	local errors=0

	# Core System Checks
	echo -e "${BLUE}Core System${NC}"

	# CPU Load
	local cpu_load=$(uptime | awk -F'load average:' '{print $2}' | awk '{print $1}' | tr -d ',' | cut -d'.' -f1)
	if [ -z "$cpu_load" ]; then cpu_load=0; fi

	if [ "$cpu_load" -gt "$CPU_THRESHOLD" ]; then
		echo -e "  ${RED}✗${NC} CPU Load: $cpu_load (critical)"
		errors=$((errors + 1))
		overall_status="critical"
	elif [ "$cpu_load" -gt $((CPU_THRESHOLD - 20)) ]; then
		echo -e "  ${YELLOW}⚠${NC} CPU Load: $cpu_load (warning)"
		warnings=$((warnings + 1))
		[ "$overall_status" = "healthy" ] && overall_status="warning"
	else
		echo -e "  ${GREEN}✓${NC} CPU Load: $cpu_load"
	fi

	# Memory Usage
	local mem_total=$(awk '/MemTotal/ {print $2}' /proc/meminfo)
	local mem_free=$(awk '/MemAvailable/ {print $2}' /proc/meminfo)
	local mem_used=$((mem_total - mem_free))
	local mem_percent=$((mem_used * 100 / mem_total))

	if [ "$mem_percent" -gt "$MEM_THRESHOLD" ]; then
		echo -e "  ${RED}✗${NC} Memory: ${mem_used}/${mem_total} KB (${mem_percent}%) - critical"
		errors=$((errors + 1))
		overall_status="critical"
	elif [ "$mem_percent" -gt $((MEM_THRESHOLD - 15)) ]; then
		echo -e "  ${YELLOW}⚠${NC} Memory: ${mem_used}/${mem_total} KB (${mem_percent}%) - warning"
		warnings=$((warnings + 1))
		[ "$overall_status" = "healthy" ] && overall_status="warning"
	else
		echo -e "  ${GREEN}✓${NC} Memory: ${mem_used}/${mem_total} KB (${mem_percent}%)"
	fi

	# Storage Usage
	local storage_info=$(df -k / | tail -1)
	local storage_total=$(echo "$storage_info" | awk '{print $2}')
	local storage_used=$(echo "$storage_info" | awk '{print $3}')
	local storage_percent=$(echo "$storage_info" | awk '{print $5}' | tr -d '%')

	if [ "$storage_percent" -gt "$STORAGE_THRESHOLD" ]; then
		echo -e "  ${RED}✗${NC} Storage: ${storage_used}/${storage_total} KB (${storage_percent}%) - critical"
		errors=$((errors + 1))
		overall_status="critical"
	elif [ "$storage_percent" -gt $((STORAGE_THRESHOLD - 15)) ]; then
		echo -e "  ${YELLOW}⚠${NC} Storage: ${storage_used}/${storage_total} KB (${storage_percent}%) - warning"
		warnings=$((warnings + 1))
		[ "$overall_status" = "healthy" ] && overall_status="warning"
	else
		echo -e "  ${GREEN}✓${NC} Storage: ${storage_used}/${storage_total} KB (${storage_percent}%)"
	fi

	# Uptime
	local uptime_str=$(uptime | awk '{print $3,$4}' | sed 's/,//')
	echo -e "  ${GREEN}✓${NC} Uptime: $uptime_str"

	echo ""

	# Network Checks
	echo -e "${BLUE}Network${NC}"

	# WAN connectivity
	local wan_device=$(uci -q get network.wan.device || uci -q get network.wan.ifname || echo "unknown")
	local wan_ip=$(ip -4 addr show dev "$wan_device" 2>/dev/null | grep 'inet ' | awk '{print $2}' | cut -d'/' -f1 | head -1)

	if [ -n "$wan_ip" ]; then
		echo -e "  ${GREEN}✓${NC} WAN: Connected ($wan_ip on $wan_device)"
	else
		echo -e "  ${YELLOW}⚠${NC} WAN: No IP address"
		warnings=$((warnings + 1))
		[ "$overall_status" = "healthy" ] && overall_status="warning"
	fi

	# LAN
	local lan_ip=$(uci -q get network.lan.ipaddr)
	if [ -n "$lan_ip" ]; then
		echo -e "  ${GREEN}✓${NC} LAN: Active ($lan_ip)"
	else
		echo -e "  ${RED}✗${NC} LAN: Not configured"
		errors=$((errors + 1))
		overall_status="critical"
	fi

	# Internet connectivity
	if ping -c 1 -W 2 8.8.8.8 >/dev/null 2>&1; then
		echo -e "  ${GREEN}✓${NC} Internet: Reachable"
	else
		echo -e "  ${YELLOW}⚠${NC} Internet: Not reachable"
		warnings=$((warnings + 1))
		[ "$overall_status" = "healthy" ] && overall_status="warning"
	fi

	# DNS resolution
	if nslookup google.com >/dev/null 2>&1; then
		echo -e "  ${GREEN}✓${NC} DNS: Resolving"
	else
		echo -e "  ${YELLOW}⚠${NC} DNS: Resolution failed"
		warnings=$((warnings + 1))
		[ "$overall_status" = "healthy" ] && overall_status="warning"
	fi

	echo ""

	# Security Checks
	echo -e "${BLUE}Security${NC}"

	# Firewall
	if /etc/init.d/firewall status >/dev/null 2>&1; then
		echo -e "  ${GREEN}✓${NC} Firewall: Active"
	else
		echo -e "  ${RED}✗${NC} Firewall: Inactive"
		errors=$((errors + 1))
		overall_status="critical"
	fi

	# SSH
	if /etc/init.d/dropbear status >/dev/null 2>&1 || /etc/init.d/sshd status >/dev/null 2>&1; then
		echo -e "  ${GREEN}✓${NC} SSH: Running"
	else
		echo -e "  ${YELLOW}⚠${NC} SSH: Not running"
	fi

	echo ""

	# Overall Status
	echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
	case "$overall_status" in
		healthy)
			echo -e "${GREEN}Overall Status: HEALTHY${NC} (0 errors, $warnings warnings)"
			;;
		warning)
			echo -e "${YELLOW}Overall Status: WARNING${NC} (0 errors, $warnings warnings)"
			;;
		critical)
			echo -e "${RED}Overall Status: CRITICAL${NC} ($errors errors, $warnings warnings)"
			;;
	esac
	echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
}

# Generate diagnostic report
generate_report() {
	local report_file="/tmp/secubox-diag-$(date +%Y%m%d-%H%M%S).txt"

	echo "Generating diagnostic report..."

	{
		echo "SecuBox Diagnostic Report"
		echo "Generated: $(date)"
		echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
		echo ""

		echo "=== System Information ==="
		uname -a
		echo ""

		echo "=== Board Information ==="
		ubus call system board
		echo ""

		echo "=== SecuBox Status ==="
		/usr/sbin/secubox-core status
		echo ""

		echo "=== Health Check ==="
		/usr/sbin/secubox-diagnostics health
		echo ""

		echo "=== Network Interfaces ==="
		ip addr show
		echo ""

		echo "=== Routing Table ==="
		ip route show
		echo ""

		echo "=== Installed Packages ==="
		opkg list-installed
		echo ""

		echo "=== System Logs (last 100 lines) ==="
		logread | tail -100
		echo ""

		echo "=== Process List ==="
		ps aux
		echo ""

	} > "$report_file"

	echo "Report saved: $report_file"
	echo "Size: $(du -h "$report_file" | cut -f1)"
}

# Run specific diagnostics
run_diagnostics() {
	local target="$1"

	case "$target" in
		all|"")
			health_check
			;;
		cpu)
			echo "CPU Load: $(uptime | awk -F'load average:' '{print $2}')"
			;;
		memory)
			free -h
			;;
		storage)
			df -h
			;;
		network)
			ip addr show
			ip route show
			;;
		*)
			echo "Unknown diagnostic target: $target"
			echo "Available: all, cpu, memory, storage, network"
			;;
	esac
}

# Main command router
case "$1" in
	health)
		health_check
		;;
	run)
		run_diagnostics "$2"
		;;
	report)
		generate_report
		;;
	*)
		echo "Usage: $0 {health|run|report} [target]"
		exit 1
		;;
esac
