Files
diyvpn/diyvpn.sh

66 lines
1.5 KiB
Bash
Executable File

#!/bin/bash
set -euo pipefail
opdir="${1?Output dir missing}"
: "${HOME?HOME is not set}"
script_dir=$(dirname "$(realpath "$0")")
common_ssh_cfg_path="${DIYVPN_SSH_CFG:-$script_dir/common_sshconfig}"
diyvpn_cfg="${DIYVPN_CFG:-$HOME/.config/diyvpn/servers}"
generate() {
local cfgpath name server_ssh_cfg idle_timeout listen_port
cfgpath="$1"
name=$(basename "$cfgpath" | tr -d '[:space:]')
server_ssh_cfg="$cfgpath"/ssh_config # TODO validate
source "$cfgpath/config.rc"
idle_timeout="${IDLE_TIMEOUT:-10min}"
listen_port="${LISTEN_PORT:?LISTEN_PORT should be set}"
cat > "$opdir/diyvpnssh-$name.service" <<-EOF
[Unit]
Description=ssh to $name
StopWhenUnneeded=yes
[Service]
Type=notify
NotifyAccess=all
# TODO change to yes?
Restart=no
RuntimeDirectory=diyvpn-$name
Environment=SSH_CFG_PATH=$server_ssh_cfg
ExecStart=ssh -F "$common_ssh_cfg_path" default
EOF
cat > "$opdir/diyvpnact-$name.service" <<-EOF
[Unit]
Description=Socket activator for diyvpn to server $name
Requires=diyvpnssh-$name.service
After=diyvpnssh-$name.service
BindsTo=diyvpnssh-$name.service
[Service]
ExecStart=/usr/lib/systemd/systemd-socket-proxyd --exit-idle-time=$idle_timeout %t/diyvpn-$name/sock
EOF
cat > "$opdir/diyvpnact-$name.socket" <<-EOF
[Unit]
Description=Socket for diyvpn to server $name
[Socket]
ListenStream=$listen_port
[Install]
WantedBy=sockets.target
EOF
}
for server in "$diyvpn_cfg"/*
do
(generate "$server" "$opdir")
done