about summary refs log tree commit diff stats
path: root/mrgrctrnl
blob: af29269b132da56b1422c7303cacf59d5e91a499 (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
#!/bin/sh
# mrgrctrnl
# configurable ssh tunneler
# by Case Duckworth <acdw@acdw.net>
# version 0.1
# LICENSE: MIT

usage() {
	cat <<-END
		mrgrctrnl: make magic ssh tunnels
		usage: mrgrctrnl [-h] [-c CONF] [-d] [-k]

		-h       show this help
		-c CONF use config file CONF.
		.        default: \$XDG_CONFIG_HOME/mrgrctrnl/config
		-d       do a dry run: don't actually tunnel
		-k       kill all processes and exit

	END
	exit "${1:-0}"
}

die() {
	[ "$#" -eq 0 ] && exit 1
	case "$1" in
	0-9*)
		ec="$1"
		shift
		;;
	*) ec=1 ;;
	esac
	printf '!!%s: %s\n' "mrgrctrnl" "$*"
	exit "$ec"
}

demolish_tunnels() {
	printf '%s...' "Demolishing tunnels"
	if [ -f "$pidf" ]; then
		while read -r pid; do
			[ -z "$pid" ] && continue
			kill "$pid" 2>/dev/null
		done <"$pidf"
		rm "$pidf"
	else
		pkill -x ssh
	fi
	printf '%s.\n' "Done"
}

config="${XDG_CONFIG_HOME:=$HOME/.config}/mrgrctrnl/config"
pidf=/tmp/mrgrctrnl.pid
dry_run=false

while getopts hc:dkr opt; do
	case "$opt" in
	h) usage ;;
	c) config="$OPTARG" ;;
	d) dry_run=true ;;
	k)
		demolish_tunnels
		pkill -x mrgrctrnl
		exit
		;;
	r)
		demolish_tunnels
		exec mrgrctrnl
		exit
		;;
	\?) usage 2 ;;
	*) usage 2 ;;
	esac
done
shift "$((OPTIND - 1))"

[ -f "$config" ] || die "Need a config! Edit $config"
if [ -e "$pidf" ] && ! "$dry_run"; then
	demolish_tunnels
fi

awk '{sub(/#.*$/,"");print}' "$config" |
	while read -r machine user local remote key rest; do
		if [ -z "$machine" ] || [ -z "$user" ] ||
			[ -z "$local" ] || [ -z "$remote" ]; then
			continue
		fi

		set -- -N "$user@$machine" -L "$local:$remote"
		[ -n "$key" ] && set -- "$@" -i "$key"
		#shellcheck disable=2086
		[ -n "$rest" ] && set -- "$@" $rest

		echo ssh "$@"

		touch "$pidf"
		"$dry_run" || {
			while [ -f "$pidf" ]; do
				ssh "$@" || break
				echo "$!" >>"$pidf"
			done &
		}
	done

wait