#!/usr/bin/env bash
# Step 01: Enable WSL2 in the VM, install Ubuntu, smoke-test.
# This is the critical nested-virtualization test.

step_name="Enable WSL2 and install Ubuntu"

run() {
  log_info "Enabling Windows Subsystem for Linux..."
  vm_exec ps "dism /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart" \
    --timeout "$TIMEOUT_INSTALL"

  log_info "Enabling Virtual Machine Platform..."
  vm_exec ps "dism /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart" \
    --timeout "$TIMEOUT_INSTALL"

  log_info "Rebooting VM for feature activation..."
  "$VBOXMANAGE" controlvm "$VM_NAME" reset
  sleep 5
  wait_for_guest "$TIMEOUT_INSTALL"

  log_info "Setting WSL default version to 2..."
  vm_exec ps "wsl --set-default-version 2" --timeout 120 || true

  log_info "Installing Ubuntu distro (this may take several minutes)..."
  vm_exec ps "wsl --install -d Ubuntu --no-launch" --timeout "$TIMEOUT_INSTALL"

  # Ubuntu needs to be launched once to complete initial setup.
  # Use --exec to avoid the interactive username prompt — we'll set up a user via root.
  log_info "Initializing Ubuntu distro..."
  vm_exec cmd "wsl -d Ubuntu -- echo 'WSL Ubuntu initialized'" --timeout 120 || true

  # Create a non-root user for PostgreSQL compatibility
  log_info "Creating test user in Ubuntu..."
  vm_exec cmd "wsl -d Ubuntu -- bash -c \"useradd -m -s /bin/bash testuser 2>/dev/null; echo 'testuser ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers\"" || true

  log_info "Updating apt cache in Ubuntu..."
  vm_exec cmd "wsl -d Ubuntu -- bash -c \"apt-get update -qq\"" --timeout 300

  # Enable systemd (needed for PostgreSQL)
  log_info "Enabling systemd in WSL..."
  vm_exec cmd "wsl -d Ubuntu -- bash -c \"echo -e '[boot]\\nsystemd=true' > /etc/wsl.conf\""

  # Restart WSL to pick up systemd config
  log_info "Restarting WSL for systemd..."
  vm_exec ps "wsl --shutdown" || true
  sleep 5

  # Take WSL snapshot so future failures can restore to this point
  log_info "Taking WSL snapshot..."
  "$VBOXMANAGE" snapshot "$VM_NAME" take "$SNAPSHOT_WSL" \
    --description "Windows + WSL2 + Ubuntu, systemd enabled"
  log_pass "Snapshot '$SNAPSHOT_WSL' saved"
}

verify() {
  log_info "Smoke-testing WSL2 (nested virtualization check)..."
  local result
  result=$(vm_exec cmd "wsl -d Ubuntu -- bash -c \"echo NESTED_VIRT_OK\"" 2>/dev/null || echo "")

  if echo "$result" | grep -q "NESTED_VIRT_OK"; then
    log_pass "WSL2 nested virtualization works"
    return 0
  else
    log_fail "WSL2 failed inside the VM — nested virtualization is not supported in this configuration"
    log_info "Re-run with --skip-wsl to test only Windows-side tools"
    return 1
  fi
}
