aboutsummaryrefslogtreecommitdiff
path: root/bin/swr
blob: 56ab59199e4aabbc560114c0cd4d3b4496b01f2f (plain) (blame)
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
#!/bin/sh
# Transparently wrap scp(1) targets on the command line
self=swr

# Create a temporary directory with name in $td, and handle POSIX-ish traps to
# remove it when the script exits.
td=
cleanup() {
    [ -n "$td" ] && rm -fr -- "$td"
    if [ "$1" != EXIT ] ; then
        trap - "$1"
        kill "-$1" "$$"
    fi
}
for sig in EXIT HUP INT TERM ; do
    # shellcheck disable=SC2064
    trap "cleanup $sig" "$sig"
done
td=$(mktd "$self") || exit

# Set a flag to manage resetting the positional parameters at the start of the
# loop
n=1
for arg ; do

    # If this is our first iteration, reset the shell parameters
    case $n in
        1) set -- ;;
    esac

    # Test whether this argument looks like a remote file
    if (

        # Test it contains a colon
        case $arg in
            *:*) ;;
            *) exit 1 ;;
        esac

        # Test the part before the first colon has at least one character and
        # only hostname characters
        case ${arg%%:*} in
            '') exit 1 ;;
            *[!a-zA-Z0-9-.]*) exit 1 ;;
        esac

    ) ; then

        # Looks like a remote file request; try to copy it into the temporary
        # directory, bail out completely if we can't
        dst=$td/$n
        scp -q -- "$arg" "$dst" || exit
        set -- "$@" "$dst"

    else
        # Just a plain old argument; stack it up
        set -- "$@" "$arg"
    fi

    # Bump n
    n=$((n+1))
done

# Run the command with the processed arguments
exec "$@"