#!/bin/zsh
#
# Security Monitors Controller
# Main entry point for running all security monitors
# Usage: ./security-monitors.sh [command]
#   check-all    - Run all monitors once
#   ssh          - Run SSH monitor only
#   disk         - Run disk monitor only
#   audit        - Run config audit only
#   init         - Initialize config audit baselines
#   report       - Show config audit report
#   status       - Show monitor status
#   install      - Install cron jobs
#   uninstall    - Remove cron jobs
#

SCRIPT_DIR="/Users/mattbruce/.openclaw/workspace/scripts/security-monitors"
LOG_DIR="$SCRIPT_DIR/logs"
STATE_DIR="$SCRIPT_DIR/state"

# Create directories
mkdir -p "$LOG_DIR" "$STATE_DIR"

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

# Helper functions
log_info() {
  echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
  echo -e "${GREEN}[OK]${NC} $1"
}

log_warn() {
  echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
  echo -e "${RED}[ERROR]${NC} $1"
}

# Run individual monitors
run_ssh_monitor() {
  log_info "Running SSH failed login monitor..."
  "$SCRIPT_DIR/ssh-monitor.sh"
  log_success "SSH monitor completed"
}

run_disk_monitor() {
  log_info "Running disk space monitor..."
  "$SCRIPT_DIR/disk-monitor.sh"
  log_success "Disk monitor completed"
}

run_config_audit() {
  log_info "Running config audit..."
  "$SCRIPT_DIR/config-audit.sh" check
  log_success "Config audit completed"
}

# Initialize baselines
init_baselines() {
  log_info "Initializing config audit baselines..."
  "$SCRIPT_DIR/config-audit.sh" init
  log_success "Baselines initialized"
}

# Show status
show_status() {
  echo ""
  echo "========================================"
  echo "    OpenClaw Security Monitors Status"
  echo "========================================"
  echo ""
  
  # Check if scripts exist and are executable
  local all_ok=true
  for script in ssh-monitor.sh disk-monitor.sh config-audit.sh; do
    if [[ -x "$SCRIPT_DIR/$script" ]]; then
      log_success "$script exists and is executable"
    else
      log_error "$script missing or not executable"
      all_ok=false
    fi
  done
  
  echo ""
  
  # Check state files
  if [[ -d "$STATE_DIR" ]]; then
    local baseline_count=$(ls -1 "$STATE_DIR/baselines" 2>/dev/null | wc -l | tr -d ' ')
    log_info "Baselines created: $baseline_count files"
  else
    log_warn "State directory not initialized"
  fi
  
  echo ""
  
  # Check for pending alerts
  if [[ -f "$STATE_DIR/alerts.queue" ]] && [[ -s "$STATE_DIR/alerts.queue" ]]; then
    local alert_count=$(wc -l < "$STATE_DIR/alerts.queue" | tr -d ' ')
    log_warn "Pending alerts in queue: $alert_count"
  else
    log_success "No pending alerts"
  fi
  
  echo ""
  
  # Show cron jobs
  echo "Current cron jobs for security monitors:"
  crontab -l 2>/dev/null | grep "security-monitors" || echo "  (none installed)"
  
  echo ""
  
  # Show last log entries
  echo "Recent log entries:"
  for log in ssh-monitor.log disk-monitor.log config-audit.log; do
    if [[ -f "$LOG_DIR/$log" ]]; then
      local last_entry=$(tail -1 "$LOG_DIR/$log" 2>/dev/null)
      echo "  $log: $last_entry"
    fi
  done
  
  echo ""
}

# Install cron jobs
install_cron() {
  log_info "Installing security monitor cron jobs..."
  
  # Get current crontab
  local current_crontab
  current_crontab=$(crontab -l 2>/dev/null || echo "")
  
  # Remove any existing security monitor entries
  current_crontab=$(echo "$current_crontab" | grep -v "security-monitors" || echo "")
  
  # Add new entries
  local new_crontab="${current_crontab}
# OpenClaw Security Monitors - $(date '+%Y-%m-%d')
*/1 * * * * $SCRIPT_DIR/ssh-monitor.sh >> $LOG_DIR/ssh-cron.log 2>&1
*/5 * * * * $SCRIPT_DIR/disk-monitor.sh >> $LOG_DIR/disk-cron.log 2>&1
0 6 * * * $SCRIPT_DIR/config-audit.sh check >> $LOG_DIR/audit-cron.log 2>&1
"
  
  # Install new crontab
  echo "$new_crontab" | crontab -
  
  log_success "Cron jobs installed:"
  log_info "  - SSH monitor: every 1 minute"
  log_info "  - Disk monitor: every 5 minutes"
  log_info "  - Config audit: daily at 6:00 AM"
}

# Uninstall cron jobs
uninstall_cron() {
  log_info "Removing security monitor cron jobs..."
  
  local current_crontab
  current_crontab=$(crontab -l 2>/dev/null || echo "")
  
  # Remove security monitor entries
  local new_crontab=$(echo "$current_crontab" | grep -v "security-monitors" || echo "")
  
  # Install updated crontab
  echo "$new_crontab" | crontab -
  
  log_success "Cron jobs removed"
}

# Main command handler
case "${1:-status}" in
  check-all)
    run_ssh_monitor
    run_disk_monitor
    run_config_audit
    log_success "All monitors completed"
    ;;
  ssh)
    run_ssh_monitor
    ;;
  disk)
    run_disk_monitor
    ;;
  audit)
    run_config_audit
    ;;
  init)
    init_baselines
    ;;
  report)
    "$SCRIPT_DIR/config-audit.sh" report
    ;;
  status)
    show_status
    ;;
  install)
    install_cron
    ;;
  uninstall)
    uninstall_cron
    ;;
  help|--help|-h)
    echo "OpenClaw Security Monitors Controller"
    echo ""
    echo "Usage: $0 [command]"
    echo ""
    echo "Commands:"
    echo "  check-all    Run all monitors once"
    echo "  ssh          Run SSH monitor only"
    echo "  disk         Run disk monitor only"
    echo "  audit        Run config audit only"
    echo "  init         Initialize config audit baselines"
    echo "  report       Show config audit report"
    echo "  status       Show monitor status"
    echo "  install      Install cron jobs"
    echo "  uninstall    Remove cron jobs"
    echo "  help         Show this help"
    echo ""
    ;;
  *)
    log_error "Unknown command: $1"
    echo "Use '$0 help' for usage information"
    exit 1
    ;;
esac
