#!/bin/bash UNIT=socat-dns default_dest=149.56.44.185 default_port=53 verify_service_availability() { dig . @127.0.0.1 >/dev/null 2>&1 } service_launch_command() { local dest port local_port dest=${1:-$default_dest} case "$dest" in '') return 1 ;; *:*) port=${dest#*:} dest=${dest%%:*} ;; *) port=${2:-$default_port} ;; esac local_port=${3:-$port} printf "socat UDP-RECVFROM:%s,fork UDP-SENDTO:%s\n" "$local_port" "$dest:$port" } #### watchdog() { PID=$1 VERIFY=$2 TWO_MILLION=2000000 SLEEP_TIME=$(( ${WATCHDOG_USEC:-$TWO_MILLION} / $TWO_MILLION )) enable -f /usr/lib/bash/sleep sleep || true while $VERIFY do systemd-notify --pid="$PID" WATCHDOG=1 sleep "$SLEEP_TIME" done } main() { case "$1" in install) shift COMMAND=$(service_launch_command "$@") if systemctl is-active "$UNIT" >/dev/null then systemctl stop "$UNIT" fi systemctl reset-failed "$UNIT" 2>/dev/null systemd-run \ --unit "$UNIT" \ --property Restart="always" \ --property WatchdogSec="5" \ -- \ "$0" watchdog "$COMMAND" verify_service_availability ;; watchdog) shift watchdog $$ "$2" & exec $1 ;; status) systemctl status "$UNIT" ;; monitor) journalctl -u "$UNIT" -f ;; *) echo "Usage: $0 install [destination [destination port [local port]]]" >&2 echo " $0 status" >&2 exit 1 ;; esac } main "$@"