

#use ssh.nu * 
export def cluster_get_file [
    settings: record
    cluster: record
    server: record
    live_ip: string 
    req_sudo: bool
    local_mode: bool
]: nothing -> bool {
    let target_path = ($cluster.target_path | default "")
    if $target_path == "" { 
        _print $"🛑 No (_ansi red_bold)target_path(_ansi reset) found in ($server.hostname) cluster ($cluster.name)"
        return false
    }
    let source_path = ($cluster.soruce_path | default "")
    if $source_path == ""  { 
        _print $"🛑 No (_ansi red_bold)source_path(_ansi reset) found in ($server.hostname) cluster ($cluster.name)"
        return false
    }
    if $local_mode { 
        let res = (^cp $source_path $target_path | combine) 
        if $res.exit_code != 0 { 
            _print $"🛑 Error get_file [ local-mode ] (_ansi red_bold)($source_path) to ($target_path)(_ansi reset) in ($server.hostname) cluster ($cluster.name)"
            _print $res.stdout
            return false
        }  
        return true
    }
    let ip = if $live_ip != ""  {
        $live_ip 
    } else { 
        #use ../../../providers/prov_lib/middleware.nu mw_get_ip
        (mw_get_ip $settings $server $server.liveness_ip false)
    }
    let ssh_key_path = ($server.ssh_key_path | default "")
    if $ssh_key_path == ""  { 
        _print $"🛑 No (_ansi red_bold)ssh_key_path(_ansi reset) found in ($server.hostname) cluster ($cluster.name)"
        return false
    }
    if not ($ssh_key_path | path exists)  { 
        _print $"🛑 Error (_ansi red_bold)($ssh_key_path)(_ansi reset) not found for ($server.hostname) cluster ($cluster.name)"
        return false
    }
    mut cmd = if $req_sudo { "sudo" } else { "" }
    let wk_path = $"/home/($env.SSH_USER)/($source_path| path basename)"
    $cmd =  $"($cmd) cp ($source_path) ($wk_path); sudo chown ($env.SSH_USER) ($wk_path)" 
        let wk_path = $"/home/($env.SSH_USER)/($source_path | path basename)"
    let res = (ssh_cmd $settings $server false $cmd $ip )
    if not $res { return false }
    if not (scp_from $settings $server $wk_path $target_path $ip ) {
        return false
    }
    let rm_cmd = if $req_sudo { 
        $"sudo rm -f ($wk_path)" 
    } else { 
        $"rm -f ($wk_path)" 
    }
    return (ssh_cmd $settings $server false $rm_cmd $ip )
}
