#!/bin/bash
# Enable root SSH login for LXC container (VMID 5000)
# This allows SSH access as root user

set -euo pipefail

VMID="${1:-5000}"
PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"

# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
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"; }

echo "════════════════════════════════════════"
echo "Enable Root SSH for Container $VMID"
echo "════════════════════════════════════════"
echo ""

# Find container node
log_info "Finding container location..."
CONTAINER_NODE=$(ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" \
    "for node in ml110 pve pve2; do \
        if pvesh get /nodes/\$node/lxc/$VMID/status/current 2>/dev/null | grep -q status; then \
            echo \$node; break; \
        fi; \
    done" 2>/dev/null || echo "")

if [ -z "$CONTAINER_NODE" ]; then
    log_warn "Container VMID $VMID not found"
    exit 1
fi

log_success "Container found on node: $CONTAINER_NODE"
echo ""

# Enable root SSH via pct exec
log_info "Enabling root SSH login..."

# Method 1: Modify sshd_config to permit root login
log_info "Configuring SSH to allow root login..."

# Create command to enable root SSH
SSH_ENABLE_CMD='
# Backup original sshd_config
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup.$(date +%Y%m%d_%H%M%S)

# Enable root login
sed -i "s/#PermitRootLogin prohibit-password/PermitRootLogin yes/" /etc/ssh/sshd_config
sed -i "s/PermitRootLogin prohibit-password/PermitRootLogin yes/" /etc/ssh/sshd_config
sed -i "s/#PermitRootLogin no/PermitRootLogin yes/" /etc/ssh/sshd_config
sed -i "s/PermitRootLogin no/PermitRootLogin yes/" /etc/ssh/sshd_config

# If PermitRootLogin line doesn't exist, add it
if ! grep -q "^PermitRootLogin" /etc/ssh/sshd_config; then
    echo "PermitRootLogin yes" >> /etc/ssh/sshd_config
fi

# Restart SSH service
systemctl restart sshd 2>/dev/null || service ssh restart 2>/dev/null || /etc/init.d/ssh restart 2>/dev/null

echo "Root SSH enabled successfully"
'

# Execute via pct exec
log_info "Applying SSH configuration..."
if ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" \
    "pct exec $VMID -- bash -c '$SSH_ENABLE_CMD'" 2>&1; then
    log_success "Root SSH enabled!"
else
    log_warn "Command execution may have issues. Trying alternative method..."
    echo ""
    echo "Please run these commands manually:"
    echo "  ssh root@$PROXMOX_HOST"
    echo "  pct enter $VMID"
    echo "  # Then run the commands inside the container"
fi

echo ""
echo "════════════════════════════════════════"
echo "Verification"
echo "════════════════════════════════════════"
echo ""
echo "To verify root SSH is enabled:"
echo "  1. Wait a few seconds for SSH service to restart"
echo "  2. Try: ssh root@192.168.11.140"
echo "  3. Password: L@kers2010"
echo ""

