#!/usr/bin/env nu
# n8n Workflow Automation - Pre-installation Environment Preparation Script
# Purpose: Set up directories, copy SSH keys, prepare configuration
# Author: JesusPerezLorenzo
# Release: 1.0

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

# Main execution
def main [] {
    print $"(_ansi green_bold)n8n(_ansi reset) Preparing environment..."

    # Load infrastructure definitions
    let defs = load_defs

    # Get n8n configuration
    let n8n_config = $defs.taskserv? | default {}
    let work_path = $env.PROVISIONING_WK_ENV_PATH

    print $"  Work path: ($work_path)"

    # Create required directories
    _create_directories $work_path

    # Copy SSH keys if configured
    _copy_ssh_keys $work_path $n8n_config

    # Copy or create custom configuration if needed
    _setup_configuration $work_path

    print $"(_ansi green)✓(_ansi reset) Environment preparation complete"
}

# Create required directory structure for n8n
def _create_directories [work_path: string] {
    let dirs = [
        $"($work_path)/data",
        $"($work_path)/logs",
        $"($work_path)/workflows",
        $"($work_path)/credentials",
        $"($work_path)/certs",
        $"($work_path)/config"
    ]

    for dir in $dirs {
        if not ($dir | path exists) {
            mkdir -p $dir
            log_debug $"Created directory: ($dir)"
        }
    }
}

# Copy SSH keys to work path if configured
def _copy_ssh_keys [work_path: string, config: record] {
    let ssh_keys = ($config.ssh_keys? | default "") | str trim

    if $ssh_keys == "" {
        log_debug "No SSH keys configured"
        return
    }

    # Create .ssh directory
    let ssh_dir = $"($work_path)/.ssh"
    mkdir -p $ssh_dir

    # Copy each configured SSH key
    for key_path in ($ssh_keys | split row " " | each { |x| $x | str trim }) {
        if $key_path == "" {
            continue
        }

        let expanded_path = $key_path | str replace "~" $env.HOME

        # Copy private key
        if ($expanded_path | path exists) {
            cp $expanded_path $"($ssh_dir)/"
            log_debug $"Copied SSH key: ($expanded_path)"
        }

        # Copy public key if it exists
        let pub_key = $"($expanded_path).pub"
        if ($pub_key | path exists) {
            cp $pub_key $"($ssh_dir)/"
            log_debug $"Copied SSH public key: ($pub_key)"
        }
    }

    # Set correct permissions for SSH directory
    chmod 700 $ssh_dir
    chmod 600 $"($ssh_dir)/"*
}

# Setup custom configuration if provided
def _setup_configuration [work_path: string] {
    let config_template = "custom.json"

    if ($config_template | path exists) {
        cp $config_template $"($work_path)/config/"
        log_debug $"Copied custom configuration: ($config_template)"
    }
}

# Run main function
main
