Last active
May 11, 2020 01:20
-
-
Save mmerickel/26e85ecc33705f4b325626bb46122f0a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
set -eEo pipefail | |
SSH_TRACE= | |
[[ "$TRACE" = "1" ]] && set -x && SSH_TRACE="-vvv" | |
SSH_TARGET=merickel.org | |
CONTROL_PATH=$(pwd)/.ssh-${SSH_TARGET} | |
SOCKET_PATH=$(pwd)/docker.sock | |
log() { | |
echo "$@" 1>&2 | |
} | |
info() { | |
log "[info]" "$@" | |
} | |
debug() { | |
log "[debug]" "$@" | |
} | |
abort() { | |
log "[error]" "$@" | |
exit 1 | |
} | |
is_running() { | |
ssh -S "$CONTROL_PATH" -O check "$SSH_TARGET" > /dev/null 2>&1 | |
} | |
start() { | |
info "starting tunnel ..." | |
rm -f "$SOCKET_PATH" "$CONTROL_PATH" | |
ssh $SSH_TRACE \ | |
-M -S "$CONTROL_PATH" -o ControlPersist=no \ | |
-fNT -L "$SOCKET_PATH:/var/run/docker.sock" \ | |
"$SSH_TARGET" | |
debug "tunnel started" | |
} | |
start_if_needed() { | |
if ! is_running; then | |
start | |
fi | |
} | |
sub_start() { | |
if is_running; then | |
abort "tunnel is already running" | |
fi | |
start | |
} | |
sub_stop() { | |
if ! is_running; then | |
abort "tunnel is not running" | |
fi | |
ssh $SSH_TRACE -S "$CONTROL_PATH" -O exit "$SSH_TARGET" | |
rm -f "$SOCKET_PATH" "$CONTROL_PATH" | |
} | |
sub_check() { | |
if is_running; then | |
info "tunnel is running" | |
else | |
abort "tunnel is not running" | |
fi | |
} | |
sub_env() { | |
start_if_needed | |
echo "export DOCKER_HOST=unix://$SOCKET_PATH" | |
} | |
sub_exec() { | |
# shellcheck source=/dev/null | |
source <(sub_env) | |
exec "$@" | |
} | |
subcommand=$1 | |
shift | |
if ! declare -f "sub_$subcommand" > /dev/null 2>&1; then | |
abort "\"$subcommand\" is not a valid subcommand" | |
fi | |
"sub_${subcommand}" "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment