#!/bin/sh
# Starts twg-client the way /etc/twg/client.toml asks, for the systemd
# service. The client has no single configuration file covering its three
# ways of connecting, so this helper picks the command line:
#   link = "twg://..."      -> twg-client connect <link>
#   control = "https://..." -> twg-client account --control <url> [--email ...]
#   a [peer] section        -> twg-client run --config /etc/twg/client.toml
# Only top-level `key = "value"` lines are read; lines starting with # are
# comments.
set -eu

CONFIG="${TWG_CONFIG:-/etc/twg/client.toml}"
STATE_DIR="${STATE_DIRECTORY:-/var/lib/twg}"
BIN=/usr/bin/twg-client

if [ ! -r "$CONFIG" ]; then
  echo "twg-client: cannot read $CONFIG" >&2
  exit 78
fi

# Value of a top-level `key = "value"` line, empty when absent or commented.
value() {
  sed -n "s/^[[:space:]]*$1[[:space:]]*=[[:space:]]*\"\([^\"]*\)\".*/\1/p" "$CONFIG" | head -n 1
}

LINK="$(value link)"
CONTROL="$(value control)"
EMAIL="$(value email)"
PASSWORD="$(value password)"
NODE="$(value node)"
OPTIONS="$(value options)"

if [ -n "$LINK" ]; then
  # shellcheck disable=SC2086 # OPTIONS is a list of arguments on purpose.
  exec "$BIN" connect "$LINK" --state-dir "$STATE_DIR" $OPTIONS
elif [ -n "$CONTROL" ]; then
  set -- account --control "$CONTROL" --state-dir "$STATE_DIR"
  [ -z "$NODE" ] || set -- "$@" --node "$NODE"
  if [ -n "$EMAIL" ]; then
    # The password goes through the environment, not the command line.
    TWG_PASSWORD="$PASSWORD"
    export TWG_PASSWORD
    set -- "$@" --email "$EMAIL"
  fi
  # shellcheck disable=SC2086
  exec "$BIN" "$@" $OPTIONS
elif grep -q '^[[:space:]]*\[peer\]' "$CONFIG"; then
  exec "$BIN" run --config "$CONFIG"
fi

# Nothing configured yet: say so and stop without an error, so that systemd
# does not keep restarting the service.
echo "twg-client: $CONFIG is not filled in yet; set link = \"twg://...\" or control = \"https://...\" and run: systemctl restart twg-client" >&2
exit 0
