#!/bin/sh
#
# Starts one tunnel for uanytun@.service from the config that
# /etc/init.d/uanytun used. ExecStart cannot do it alone, as every
# non comment line of the config becomes one --option argument
#
# --write-pid is dropped, as systemd follows the process

set -e

NAME="$1"
CONFIG_DIR="/etc/uanytun"
CONFIG="$CONFIG_DIR/$NAME/config"

DAEMONOPTS=""
[ -f "/etc/default/uanytun" ] && . "/etc/default/uanytun"

[ -f "$CONFIG" ] || {
	echo "uanytun: $CONFIG does not exist" >&2
	exit 1
}

POSTUP=""
[ -f "$CONFIG_DIR/$NAME/post-up.sh" ] && POSTUP="-x $CONFIG_DIR/$NAME/post-up.sh"

CHROOTDIR=$(sed -n 's/^chroot[[:space:]]*//p' "$CONFIG")
[ -n "$CHROOTDIR" ] && mkdir -p "$CHROOTDIR"

DAEMONARG=$(sed 's/#.*//' "$CONFIG" | grep -e '\w' | sed 's/^/--/' | tr '\n' ' ')

exec /usr/sbin/uanytun --nodaemonize $POSTUP $DAEMONOPTS $DAEMONARG
