#!/bin/bash
# Set root password for a Proxmox LXC container
# Usage: ./set-container-password.sh <VMID> <PASSWORD>

set -euo pipefail

VMID="${1:-5000}"
PASSWORD="${2:-L@kers2010}"
PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"

if [ $# -eq 0 ]; then
    echo "Usage: $0 <VMID> [PASSWORD]"
    echo "Default password: L@kers2010"
    exit 1
fi

# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }

# Find container node
log_info "Finding container VMID $VMID..."
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
    echo "❌ Container VMID $VMID not found on any node"
    exit 1
fi

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

# Set password using chpasswd
log_info "Setting root password for container $VMID..."
if ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" \
    "pvesh create /nodes/$CONTAINER_NODE/lxc/$VMID/exec --command 'bash' --arg '-c' --arg \"echo root:$PASSWORD | chpasswd\" 2>/dev/null" 2>&1 | grep -q "UPID\|success"; then
    log_success "Password set successfully via API"
elif ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" \
    "pct exec $VMID -- bash -c 'echo \"root:$PASSWORD\" | chpasswd' 2>&1"; then
    log_success "Password set successfully"
else
    echo "❌ Failed to set password"
    echo ""
    echo "Alternative methods:"
    echo "1. Via Proxmox web UI:"
    echo "   - Go to Container $VMID → Options → Password"
    echo "   - Set password: $PASSWORD"
    echo ""
    echo "2. Via container console:"
    echo "   ssh root@$PROXMOX_HOST"
    echo "   pct enter $VMID"
    echo "   passwd root"
    exit 1
fi

echo ""
log_success "Root password for container $VMID set to: $PASSWORD"
echo ""
echo "You can now login with:"
echo "  ssh root@<container-ip>"
echo "  Password: $PASSWORD"

