#!/usr/bin/env bash
# Step 06: Build and install Redis 6.2.6 from source inside WSL Ubuntu.
# Mirrors the exact commands from the cloud-setup skill.

step_name="Install Redis 6.2.6 (compile from source in WSL)"

run() {
  log_info "Installing build dependencies..."
  vm_exec wsl "sudo apt-get install -y tcl build-essential pkg-config libssl-dev" --timeout 300

  log_info "Downloading Redis 6.2.6..."
  vm_exec wsl "cd /tmp && wget -q https://download.redis.io/releases/redis-6.2.6.tar.gz" --timeout 120

  log_info "Extracting..."
  vm_exec wsl "cd /tmp && tar xzf redis-6.2.6.tar.gz"

  log_info "Compiling Redis (make -j\$(nproc))..."
  vm_exec wsl "cd /tmp/redis-6.2.6 && make -j\$(nproc)" --timeout "$TIMEOUT_INSTALL"

  log_info "Installing Redis binaries..."
  vm_exec wsl "cd /tmp/redis-6.2.6 && sudo make install" --timeout 120

  # install_server.sh prompts for port, config path, log path, data dir, executable.
  # All accept defaults with Enter. Pipe empty lines for each prompt.
  log_info "Running install_server.sh (non-interactive)..."
  vm_exec wsl "cd /tmp/redis-6.2.6/utils && printf '\\n\\n\\n\\n\\n\\n' | sudo ./install_server.sh" --timeout 60

  log_info "Starting Redis service..."
  vm_exec wsl "sudo service redis_6379 start" --timeout 30 || true
}

verify() {
  # Check version
  local ver
  ver=$(vm_exec wsl "redis-cli -v" 2>/dev/null || echo "")
  if ! echo "$ver" | grep -q "6.2"; then
    log_fail "Redis version check failed (got: $ver)"
    return 1
  fi
  log_pass "Redis version: $ver"

  # Check ping
  local ping
  ping=$(vm_exec wsl "redis-cli ping" 2>/dev/null || echo "")
  if [[ "$ping" == *"PONG"* ]]; then
    log_pass "Redis responding: PONG"
    return 0
  fi
  log_fail "Redis not responding (got: $ping)"
  return 1
}
