#!/usr/bin/env php
<?php
/**
 * WHP Security Management CLI Tool
 * 
 * Usage: php security-cli.php [command] [options]
 * 
 * Commands:
 *   list-blocked          - List all blocked IP addresses
 *   list-whitelist        - List all whitelisted IP addresses
 *   block <ip> [reason]   - Block an IP address
 *   unblock <ip>          - Unblock an IP address
 *   whitelist <ip> [desc] - Add IP to whitelist
 *   remove-whitelist <ip> - Remove IP from whitelist
 *   stats                 - Show security statistics
 *   cleanup               - Clean up expired blocks
 *   help                  - Show this help message
 */

// Set error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Check if running from command line
if (php_sapi_name() !== 'cli') {
    die("This script must be run from the command line.\n");
}

// Include required files
require_once(__DIR__ . '/../libs/security_manager.php');

// Initialize security manager
$secManager = new security_manager();

// Get command line arguments
$args = $argv;
$script_name = array_shift($args);
$command = isset($args[0]) ? $args[0] : 'help';

// Function to print colored output
function print_success($message) {
    echo "\033[32m✓ $message\033[0m\n";
}

function print_error($message) {
    echo "\033[31m✗ $message\033[0m\n";
}

function print_warning($message) {
    echo "\033[33m⚠ $message\033[0m\n";
}

function print_info($message) {
    echo "\033[34mℹ $message\033[0m\n";
}

function print_header($message) {
    echo "\033[1;36m$message\033[0m\n";
    echo str_repeat('-', strlen($message)) . "\n";
}

// Function to format timestamp
function format_time($timestamp) {
    return date('Y-m-d H:i:s', $timestamp);
}

// Function to format duration
function format_duration($seconds) {
    if ($seconds < 60) {
        return "$seconds seconds";
    } elseif ($seconds < 3600) {
        $minutes = floor($seconds / 60);
        return "$minutes minutes";
    } else {
        $hours = floor($seconds / 3600);
        $minutes = floor(($seconds % 3600) / 60);
        return "$hours hours, $minutes minutes";
    }
}

// Process commands
switch ($command) {
    case 'list-blocked':
        print_header("Blocked IP Addresses");
        $blocked_ips = $secManager->get_blocked_ips();
        
        if (empty($blocked_ips)) {
            print_info("No IP addresses are currently blocked.");
        } else {
            printf("%-15s %-20s %-20s %-30s %-8s %-6s\n", 
                "IP Address", "Blocked Since", "Unblock Time", "Reason", "Attempts", "Type");
            echo str_repeat('-', 100) . "\n";
            
            foreach ($blocked_ips as $block) {
                $type = $block['manual_block'] ? 'Manual' : 'Auto';
                $remaining = $block['unblock_time'] - time();
                $status = $remaining > 0 ? format_duration($remaining) : 'Expired';
                
                printf("%-15s %-20s %-20s %-30s %-8s %-6s\n",
                    $block['ip_address'],
                    format_time($block['block_time']),
                    $status,
                    substr($block['reason'], 0, 28) . (strlen($block['reason']) > 28 ? '..' : ''),
                    $block['failed_attempts'],
                    $type
                );
            }
        }
        break;
        
    case 'list-whitelist':
        print_header("Whitelisted IP Addresses");
        $whitelist_ips = $secManager->get_whitelist_ips();
        
        if (empty($whitelist_ips)) {
            print_info("No IP addresses in whitelist.");
        } else {
            printf("%-15s %-30s %-20s\n", "IP Address", "Description", "Added");
            echo str_repeat('-', 70) . "\n";
            
            foreach ($whitelist_ips as $whitelist) {
                printf("%-15s %-30s %-20s\n",
                    $whitelist['ip_address'],
                    substr($whitelist['description'], 0, 28) . (strlen($whitelist['description']) > 28 ? '..' : ''),
                    format_time($whitelist['added_time'])
                );
            }
        }
        break;
        
    case 'block':
        if (!isset($args[1])) {
            print_error("Usage: php security-cli.php block <ip_address> [reason]");
            exit(1);
        }
        
        $ip = $args[1];
        $reason = isset($args[2]) ? $args[2] : 'Manual block via CLI';
        
        if ($secManager->block_ip($ip, $reason)) {
            print_success("IP address $ip has been blocked. Reason: $reason");
        } else {
            print_error("Failed to block IP address $ip (may be whitelisted)");
            exit(1);
        }
        break;
        
    case 'unblock':
        if (!isset($args[1])) {
            print_error("Usage: php security-cli.php unblock <ip_address>");
            exit(1);
        }
        
        $ip = $args[1];
        
        if ($secManager->unblock_ip($ip)) {
            print_success("IP address $ip has been unblocked.");
        } else {
            print_error("Failed to unblock IP address $ip");
            exit(1);
        }
        break;
        
    case 'whitelist':
        if (!isset($args[1])) {
            print_error("Usage: php security-cli.php whitelist <ip_address> [description]");
            exit(1);
        }
        
        $ip = $args[1];
        $description = isset($args[2]) ? $args[2] : 'Added via CLI';
        
        if ($secManager->add_whitelist_ip($ip, $description)) {
            print_success("IP address $ip has been added to whitelist. Description: $description");
        } else {
            print_error("Failed to add IP address $ip to whitelist");
            exit(1);
        }
        break;
        
    case 'remove-whitelist':
        if (!isset($args[1])) {
            print_error("Usage: php security-cli.php remove-whitelist <ip_address>");
            exit(1);
        }
        
        $ip = $args[1];
        
        if ($secManager->remove_whitelist_ip($ip)) {
            print_success("IP address $ip has been removed from whitelist.");
        } else {
            print_error("Failed to remove IP address $ip from whitelist");
            exit(1);
        }
        break;
        
    case 'stats':
        print_header("Security Statistics");
        $stats = $secManager->get_security_stats();
        
        echo "Currently Blocked IPs: " . $stats['blocked_ips'] . "\n";
        echo "Failed Attempts (24h): " . $stats['failed_attempts_24h'] . "\n";
        echo "Whitelisted IPs: " . $stats['whitelist_ips'] . "\n";
        break;
        
    case 'cleanup':
        print_header("Cleaning up expired blocks and old data");
        
        if ($secManager->cleanup_expired_blocks()) {
            print_success("Cleanup completed successfully.");
        } else {
            print_error("Cleanup failed.");
            exit(1);
        }
        break;
        
    case 'help':
    default:
        print_header("WHP Security Management CLI Tool");
        echo "Usage: php security-cli.php [command] [options]\n\n";
        echo "Commands:\n";
        echo "  list-blocked                    - List all blocked IP addresses\n";
        echo "  list-whitelist                  - List all whitelisted IP addresses\n";
        echo "  block <ip> [reason]             - Block an IP address\n";
        echo "  unblock <ip>                    - Unblock an IP address\n";
        echo "  whitelist <ip> [description]    - Add IP to whitelist\n";
        echo "  remove-whitelist <ip>           - Remove IP from whitelist\n";
        echo "  stats                           - Show security statistics\n";
        echo "  cleanup                         - Clean up expired blocks\n";
        echo "  help                            - Show this help message\n\n";
        echo "Examples:\n";
        echo "  php security-cli.php list-blocked\n";
        echo "  php security-cli.php block 192.168.1.100 'Suspicious activity'\n";
        echo "  php security-cli.php unblock 192.168.1.100\n";
        echo "  php security-cli.php whitelist 192.168.1.50 'Trusted admin'\n";
        echo "  php security-cli.php stats\n";
        break;
}

echo "\n";
?> 