#!/usr/bin/env nu 
# Info: Prepare for os/basecamp installation
# Author: JesusPerezLorenzo 
# Release: 1.0.2
# Date: 19-11-2023

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

use lib_provisioning/utils/ui.nu *

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

let defs = load_defs

#sops_cmd "decrypt" /wuwei/repo-cnz/klab/basecamp/.keys.k  | save --force /tmp/ky.k

let ssh_keys = ($defs.taskserv.ssh_keys | str replace "~" $env.HOME | str trim)

if $ssh_keys != "" {
   let target_path = $env.PROVISIONING_WK_ENV_PATH
   ^mkdir -p $"($target_path)/.ssh"
   for key in ($ssh_keys | split row " ") {
     log_debug $"on ($key)"
     if ($key | path exists) { cp $key $"($target_path)/.ssh" }
     if ($"($key).pub" | path exists) { cp $"($key).pub" $"($target_path)/.ssh" }
   }
}

# Prepare Nushell installation if enabled
let install_nushell = ($defs.taskserv.install_nushell? | default false)
if $install_nushell {
    log_info "Preparing Nushell runtime installation..."

    let target_path = $env.PROVISIONING_WK_ENV_PATH
    let nushell_script = "../../nushell/default/install-nushell.sh"

    # Copy Nushell installation script if it exists
    if ($nushell_script | path exists) {
        cp $nushell_script $"($target_path)/install-nushell.sh"
        ^chmod +x $"($target_path)/install-nushell.sh"
        log_debug "Copied Nushell installation script"
    } else {
        log_warn "Nushell installation script not found at ($nushell_script)"
    }

    # Copy Nushell configuration templates
    let nushell_templates = [
        "../../nushell/default/config.nu.j2"
        "../../nushell/default/env.nu.j2"
        "../../nushell/default/remote-exec.nu.j2"
    ]

    ^mkdir -p $"($target_path)/nushell/templates"
    for template in $nushell_templates {
        if ($template | path exists) {
            let template_name = ($template | path basename)
            cp $template $"($target_path)/nushell/templates/($template_name)"
            log_debug $"Copied Nushell template: ($template_name)"
        }
    }

    # Copy observability scripts
    let observability_scripts = [
        "../../nushell/observability/collect.nu"
        "../../nushell/observability/process.nu"
        "../../nushell/observability/telemetry.nu"
    ]

    ^mkdir -p $"($target_path)/nushell/observability"
    for script in $observability_scripts {
        if ($script | path exists) {
            let script_name = ($script | path basename)
            cp $script $"($target_path)/nushell/observability/($script_name)"
            ^chmod +x $"($target_path)/nushell/observability/($script_name)"
            log_debug $"Copied observability script: ($script_name)"
        }
    }

    log_info "Nushell runtime preparation completed"
}
