Skip to content

Instantly share code, notes, and snippets.

@ColinHeathman
Created August 15, 2022 22:30
Show Gist options
  • Save ColinHeathman/ffd441f292a1e42c92835b6d639ec5a5 to your computer and use it in GitHub Desktop.
Save ColinHeathman/ffd441f292a1e42c92835b6d639ec5a5 to your computer and use it in GitHub Desktop.
#!/bin/bash
set -Eeuo pipefail
# Set up console colors
YELLOW='\033[1;33m'
RED='\033[1;31m'
CLEAR='\033[0m'
msg() {
echo >&2 -e "${YELLOW}${1-}${CLEAR}"
}
fatal() {
echo >&2 -e "${RED}${1-}${CLEAR}"
}
TERMINATION_GRACE_SECONDS="${TERMINATION_GRACE_SECONDS:-600}"
rclone serve sftp --key "${HOME}/.ssh/id_rsa" --addr :8022 --authorized-keys "${HOME}/.ssh/authorized_keys" remote:path &
RCLONE_PID=$!
socat "TCP-LISTEN:2022,fork,reuseaddr" "TCP-CONNECT:127.0.0.1:8022" &
SOCAT_PID=$!
# validate startup
sleep 2
if ! (ps | grep -q "${SOCAT_PID}" > /dev/null && ps | grep -q "${RCLONE_PID}" > /dev/null); then
fatal "Startup failed"
kill -s SIGTERM "${SOCAT_PID}"
kill -s SIGTERM "${RCLONE_PID}"
exit 1
fi
do_shutdown() {
msg "Refusing new connections"
kill -s SIGTERM "${SOCAT_PID}"
i=1
while true
do
if ! pgrep "socat" > /dev/null; then
msg "All clients disconnected"
break
fi
if [ $i -ge "${TERMINATION_GRACE_SECONDS}" ]; then
fatal "Forcefully shutting down"
break
fi
msg "Waiting for clients to disconnect"
sleep 1
i=$(( i + 1 ))
done
kill -s SIGTERM "${RCLONE_PID}"
exit 0
}
# wait for shutdown signal
trap do_shutdown SIGTERM
tail -f /dev/null & wait
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment