about summary refs log tree commit diff stats
path: root/mrgrctrnl
blob: 4f090d19fe85cdf16a6acc4e2cab023e50a3fee4 (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
#!/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]

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

	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"
}

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

while getopts hc:d opt; do
	case "$opt" in
		h) usage ;;
		c) config="$OPTARG" ;;
		d) dry_run=true ;;
		\?) usage 2 ;;
		*) usage 2 ;;
	esac
done
shift "$((OPTIND - 1))"

[ -f "$config" ] || die "Need a config! Edit $config"
[ -e "$pidf" ] && ! "$dry_run" && {
	while read -r pid; do
		kill "$pid"
	done < "$pidf"
	rm "$pidf"
}

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

	echo ssh -N "$user@$machine" -L "$local:$remote"

	$dry_run || 
	while :
	do
		ssh -N "$user@$machine" -L "$local:$remote"
		echo "$!" >> "$pidf"
		sleep 3
	done &
done

wait