summaryrefslogtreecommitdiff
path: root/src/rpc.bash
blob: eb41538a39033bb75b90ae6a0fc3c781fc4732d0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105

intersection()
{
        comm -12 "$@"
}

difference()
{
        comm -23 "$@"
}

extract_words()
{
        grep -o -E '\b\w+\b' | sort -u
}

immediate_dependencies1()
{
        intersection \
                <(compgen -A function | sort -u) \
                <(declare -f "$1" | extract_words)
}

immediate_dependencies()
{
        for f
        do
                immediate_dependencies1 "$f"
        done | sort -u
}

recursive_dependencies()
{
        seen=()
        while [ $# -gt 0 ]
        do
                seen+=("$@")
                set -- $(difference <(immediate_dependencies "$@") \
                                    <(printf '%s\n' "${seen[@]}" | sort -u))
        done
        printf '%s\n' "${seen[@]}"
}








# Input: $BASH_RPC_REMOTE_DEST - hostname passed to ssh (uses ssh host aliases)
# Input: $BASH_RPC_SSH_OPTIONS - option arguments passed to ssh (they precede '--')
# Input: $1 - bash shell script source code to run remotely
# Input: $2, $3, ... - command line arguments passed to the remote bash shell
# Input: stdin, stdout, stderr: passed to ssh
bash_rpc_remote_run_script()
{
        (
                local script="$1"
                shift
                set -- "$SHELL" -c "${script@Q}" "$0" "${@@Q}"
                set -x
                exec ssh \
                        "${BASH_RPC_SSH_OPTIONS[@]}" \
                        -- \
                        "${BASH_RPC_REMOTE_DEST:-localhost}" \
                        "$@"
        )
}

# Preserves the rest of stdin for the command.
bash_rpc_eval_stdin()
{
        [ "$1" -gt 0 ] || return
        read -N"$1" -r || return
        shift # prepare "$@" for script execution context
        source <(printf '%s' "$REPLY" | tr -d '\015')
}

remote_run_function_simple()
{
        script_source=$(declare -f "$1" && printf '"$@";\n')
        bash_rpc_remote_run_script "$script_source" "$@"
}

remote_run_function()
{
        main=$1
        funcs=$(recursive_dependencies "$main")
        stage2_source=$(
                declare -f $funcs
                printf '"$@"\n' "$main"
        )
        BASH_RPC_SSH_OPTIONS=(-tt)
        {
                printf '%s' "$stage2_source"
                if [ -t 0 ]
                then
                        socat stdio PTY
                else
                        cat
                fi
        } | remote_run_function_simple bash_rpc_eval_stdin "${#stage2_source}" "$@"
}