#!/usr/bin/env nu
# Info: Prepare for nushell installation on infrastructure servers
# Author: Generated by Claude Code
# Release: 1.0.0
# Date: 2025-09-23

use lib_provisioning/cmd/env.nu *
use lib_provisioning/cmd/lib.nu *
use lib_provisioning/utils/ui.nu *

print $"(_ansi green_bold)Nushell Runtime(_ansi reset) with ($env.PROVISIONING_VARS)"

let defs = load_defs

# Ensure target environment path exists
let target_path = $env.PROVISIONING_WK_ENV_PATH
^mkdir -p $"($target_path)/.config/nushell"
^mkdir -p $"($target_path)/.local/bin"
^mkdir -p $"($target_path)/.local/share/nushell"

# Create secure directory for Nushell scripts
^mkdir -p $"($target_path)/nushell/scripts"
^mkdir -p $"($target_path)/nushell/observability"
^mkdir -p $"($target_path)/nushell/lib"

# Set secure permissions for Nushell directories
^chmod 750 $"($target_path)/nushell"
^chmod 700 $"($target_path)/nushell/scripts"

# Create plugin directory if plugins are enabled
if ($defs.taskserv.nushell_plugins? | default false) {
    ^mkdir -p $"($target_path)/.local/share/nushell/plugins"
    log_debug "Created Nushell plugins directory"
}

# Copy SSH keys if specified for remote operations
let ssh_keys = ($defs.taskserv.ssh_keys? | default "" | str replace "~" $env.HOME | str trim)
if $ssh_keys != "" {
    ^mkdir -p $"($target_path)/.ssh"
    for key in ($ssh_keys | split row " ") {
        log_debug $"Setting up SSH key: ($key)"
        if ($key | path exists) {
            cp $key $"($target_path)/.ssh"
            ^chmod 600 $"($target_path)/.ssh/($key | path basename)"
        }
        if ($"($key).pub" | path exists) {
            cp $"($key).pub" $"($target_path)/.ssh"
            ^chmod 644 $"($target_path)/.ssh/($key | path basename).pub"
        }
    }
}

# Ensure proper ownership for security
let admin_user = ($defs.taskserv.admin_user? | default "root")
^chown -R $"($admin_user):($admin_user)" $"($target_path)/nushell"

log_info "Nushell environment prepared successfully"