summaryrefslogtreecommitdiff
path: root/src/rpc.bash
blob: 644df95a59154383c7168f21ded66920233444fc (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

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

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

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

read_len()
{
        REPLY=
        [ "$1" -gt 0 ] && read -r -N"$1" && [ "$REPLY" ]
}

read_remote_command()
{
        read_len "$1"
        shift
        remote_command=(bash -c "${REPLY@Q}" bash "${@@Q}")
}

remote_run_shell_script_stdin()
{
        read_remote_command "$@"
        ssh    -- "${REMOTE_DEST}" "${remote_command[@]}"
}

remote_run_shell_script_tty()
{
        read_remote_command "$@"
        ssh -t -- "${REMOTE_DEST}" "${remote_command[@]}" </dev/tty
}

remote_run_shell_script_arg1()
{
        script=$1
        shift
        set -- "${#script}" "$@"
        if test -t 0 && test -t 1
        then
                printf '%s' "$script" |
                        remote_run_shell_script_tty "$@"
        else
                cat <(printf '%s' "$script") - |
                        remote_run_shell_script_stdin "$@"
        fi
}

immediate_dependencies1()
{
        # Thanks Lri from stackoverflow.com/questions/4471364/
        # how-do-i-list-the-functions-defined-in-my-shell/28278090
        intersection \
                <(compgen -A function | sort -u) \
                <(declare -f "$1" | extract_words)
}

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

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

remote_run_function()
{
        main=$1
        shift
        funcs=$(recursive_dependencies "$main")

        script=
        read -N2147483647 -r script < <(
                declare -f $funcs
                printf '%s "$@";\n' "$main"
        ) || true
        [ "$script" ]

        remote_run_shell_script_arg1 "$script" "$@"
}