#!/usr/bin/env bash
# Set Root Password for Proxmox LXC Container - Correct Method
# Must be run on Proxmox host

set -euo pipefail

VMID="${1:-2500}"
PASSWORD="${NEW_PASSWORD:-${2:-}}"

if [ -z "${PASSWORD}" ]; then
    echo "ERROR: NEW_PASSWORD is required. Pass it as an argument or export NEW_PASSWORD in the environment." >&2
    echo "       Hardcoded default removed for security; see docs/SECURITY.md." >&2
    exit 2
fi

if ! command -v pct >/dev/null 2>&1; then
    echo "Error: pct command not found"
    echo "This script must be run on the Proxmox host"
    exit 1
fi

echo "Setting root password for VMID $VMID..."
echo "Password: $PASSWORD"
echo ""

# Method 1: Use pct exec to run passwd command
echo "Method 1: Using pct exec with echo and passwd..."
echo "$PASSWORD" | pct exec "$VMID" -- passwd root 2>&1 || {
    echo "Method 1 failed, trying alternative..."
    
    # Method 2: Use pct enter (interactive)
    echo ""
    echo "Method 2: Interactive method"
    echo "Run the following command manually:"
    echo "  echo '$PASSWORD' | pct exec $VMID -- passwd root"
    echo ""
    echo "Or enter the container and set password:"
    echo "  pct enter $VMID"
    echo "  passwd root"
    echo "  (enter password when prompted)"
    echo "  exit"
    echo ""
    
    # Method 3: Use chpasswd
    echo "Method 3: Using chpasswd..."
    echo "root:$PASSWORD" | pct exec "$VMID" -- chpasswd 2>&1 && {
        echo "✅ Password set successfully using chpasswd"
        exit 0
    } || {
        echo "Method 3 also failed"
        echo ""
        echo "Trying direct passwd with stdin..."
    }
}

# Method 4: Direct passwd with expect-like approach
echo ""
echo "Attempting direct password setting..."
(echo "$PASSWORD"; echo "$PASSWORD") | pct exec "$VMID" -- passwd root 2>&1 && {
    echo "✅ Password set successfully"
} || {
    echo ""
    echo "⚠️  Automated methods failed. Use manual method:"
    echo ""
    echo "Manual Method 1 (Interactive):"
    echo "  pct enter $VMID"
    echo "  passwd root"
    echo "  (enter: $PASSWORD)"
    echo "  exit"
    echo ""
    echo "Manual Method 2 (One-liner):"
    echo "  pct exec $VMID -- bash -c \"echo 'root:$PASSWORD' | chpasswd\""
    echo ""
    echo "Manual Method 3 (SSH if already accessible):"
    echo "  ssh root@<container-ip>"
    echo "  passwd root"
    echo "  (enter: $PASSWORD)"
}

