#!/bin/bash
# Proxmox Security Hardening Script
# Implements security best practices for Proxmox hosts

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/load-physical-inventory.sh" 2>/dev/null || true

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[⚠]${NC} $1"; }
log_error() { echo -e "${RED}[✗]${NC} $1"; }
log_section() { echo -e "\n${CYAN}=== $1 ===${NC}\n"; }

# Hosts
declare -A HOSTS
HOSTS[r630-01]="${PROXMOX_HOST_R630_01:-192.168.11.11}:${PROXMOX_PASS_R630_01:-password}"
HOSTS[r630-02]="${PROXMOX_HOST_R630_02:-192.168.11.12}:${PROXMOX_PASS_R630_02:-password}"

log_section "Proxmox Security Hardening"

log_warn "This script will:"
log_warn "1. Review current security settings"
log_warn "2. Provide recommendations"
log_warn "3. Optionally apply security improvements"
echo ""

read -p "Continue with security review? (yes/no): " confirm
if [[ "$confirm" != "yes" ]]; then
    log_info "Security review cancelled."
    exit 0
fi

# Security Review
for hostname in "${!HOSTS[@]}"; do
    ip="${HOSTS[$hostname]%%:*}"
    password="${HOSTS[$hostname]#*:}"
    
    log_section "Security Review: $hostname ($ip)"
    
    sshpass -p "$password" ssh -o StrictHostKeyChecking=no root@"$ip" bash <<'ENDSSH' 2>/dev/null || {
        log_error "Could not connect to ${hostname}"
        continue
    }
        echo "=== SSH Configuration ==="
        grep -E "^PermitRootLogin|^PasswordAuthentication|^PubkeyAuthentication" /etc/ssh/sshd_config 2>/dev/null || echo "SSH config not readable"
        echo ""
        
        echo "=== Firewall Status ==="
        if command -v pve-firewall >/dev/null 2>&1; then
            pve-firewall status 2>/dev/null || echo "Firewall status unknown"
        else
            echo "pve-firewall not available"
        fi
        echo ""
        
        echo "=== Failed Login Attempts ==="
        lastb 2>/dev/null | head -5 || echo "No failed login records"
        echo ""
        
        echo "=== Recent Logins ==="
        last -5 2>/dev/null | head -5 || echo "No recent login records"
        echo ""
        
        echo "=== User Accounts ==="
        awk -F: '$3 == 0 {print $1}' /etc/passwd
        echo ""
        
        echo "=== Sudo Configuration ==="
        if [ -f /etc/sudoers ]; then
            echo "sudoers file exists"
            grep -v "^#" /etc/sudoers | grep -v "^$" | head -5 || echo "No sudo rules found"
        fi
        echo ""
        
        echo "=== Proxmox API Access ==="
        pveum user list 2>/dev/null | head -10 || echo "Cannot list users"
        echo ""
ENDSSH
done

log_section "Security Recommendations"

cat <<'RECOMMENDATIONS'
1. SSH Security:
   - Disable root password login (use SSH keys)
   - Change default passwords
   - Enable key-based authentication only

2. Firewall:
   - Enable pve-firewall
   - Restrict access to Proxmox web interface (8006)
   - Only allow necessary ports

3. User Management:
   - Create non-root users with sudo
   - Use Proxmox roles and permissions
   - Review API tokens regularly

4. Updates:
   - Keep Proxmox and packages updated
   - Enable automatic security updates
   - Monitor security advisories

5. Monitoring:
   - Monitor failed login attempts
   - Set up log aggregation
   - Alert on security events

RECOMMENDATIONS

log_section "Security Review Complete"
log_info "Review the output above and implement recommendations as needed"
