#!/usr/bin/env bash

module_description() {
  printf "Homelab Configuration - set up Unraid server access\n"
}

module_required() { return 1; }
module_should_skip() { return 1; }

module_prereqs() {
  return 0
}

module_main() {
  log_section "Homelab Configuration"

  local homelab_config_dir="$HOME/.config/homelab"
  local homelab_config_file="$homelab_config_dir/config.yaml"

  tui_bold "Homelab Control Center Setup"
  tui_info "This configures SSH access and connection details to your Unraid server."
  printf '\n'

  local server_address server_username

  server_address="$(tui_input "Server address (IP or domain)")"
  if [[ -z "$server_address" ]]; then
    log_info "Homelab setup skipped (no server address)"
    return 0
  fi

  server_username="$(tui_input "SSH username")"
  if [[ -z "$server_username" ]]; then
    server_username="root"
  fi

  mkdir -p "$homelab_config_dir"

  cat > "$homelab_config_file" <<CONFIG
# Homelab Configuration
# Generated by Omeron on $(date --rfc-3339=seconds)

server:
  address: "${server_address}"
  username: "${server_username}"
  port: 22

control_center:
  refresh_interval: 5
  theme: "dark"

features:
  docker: true
  services: true
  storage: true
  network: true
  monitoring: true
CONFIG

  log_success "Homelab configuration saved to $homelab_config_file"

  printf '\n'
  tui_bold "Configuration Summary:"
  tui_info "  Server address: ${server_address}"
  tui_info "  SSH username:   ${server_username}"
  printf '\n'
  tui_info "You can edit the configuration anytime at: ${homelab_config_file}"

  if tui_confirm "Test SSH connection to ${server_username}@${server_address}?"; then
    log_info "Testing SSH connection..."
    if ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=accept-new "${server_username}@${server_address}" "echo OK" 2>&1; then
      log_success "SSH connection successful"
    else
      log_warn "SSH connection failed. You may need to set up SSH keys or the server may not be reachable."
    fi
  fi
}
