#!/bin/sh
# Install, update, configure or uninstall intergate on Linux and macOS.
#
#   curl -fsSL https://jgermade.github.io/intergate/setup.sh | sh
#   curl -fsSL https://jgermade.github.io/intergate/setup.sh | sh -s -- reinstall
#   curl -fsSL https://jgermade.github.io/intergate/setup.sh | sh -s -- uninstall
#   curl -fsSL https://jgermade.github.io/intergate/setup.sh | sh -s -- setup-url
#   curl -fsSL https://jgermade.github.io/intergate/setup.sh | sh -s -- client
#   wget -qO- https://jgermade.github.io/intergate/setup.sh | sh     # without curl
#
# With no command and a terminal to ask on, it asks what to do: install, and —
# when it finds intergate already there — update, reinstall, configure, a new
# link to the dashboard's setup or uninstall. With nobody to ask it installs.
#
# One binary, from a GitHub release, into /usr/local/bin (or --dir). After a
# first install it offers `intergate config`, the setup wizard, and on Linux
# with systemd `intergate service --install`, which prints the one-time link
# to the dashboard's setup (email delivery and the owner) when the
# configuration leaves them to it. An update restarts the service.
# `uninstall` keeps the configuration and data unless `--purge` says otherwise.
#
# `client` installs intergate-tunnel instead, the client alone, for a machine
# that keeps tunnels open to a gate, and opens its wizard; `uninstall-client`
# removes it.
#
# Everything is a function and the last line calls `main`, so a download that
# was cut short runs nothing. POSIX sh, because `| sh` is dash on Debian.

set -eu

REPO="jgermade/intergate"
SETUP_URL="https://jgermade.github.io/intergate/setup.sh"
UNIT="/etc/systemd/system/intergate.service"
CLIENT_UNIT="/etc/systemd/system/intergate-tunnel.service"
CLIENT_PLIST="/Library/LaunchDaemons/io.github.jgermade.intergate-tunnel.plist"
CLIENT_CONFIG_DIR="/etc/intergate-tunnel"
TMP=""

usage() {
	cat <<EOF
intergate setup: install, update, configure or uninstall intergate.

Usage:
  curl -fsSL $SETUP_URL | sh -s -- [command] [options]
  sh setup.sh [command] [options]

Commands:
  install      Install the latest release, or update to it. Does nothing when
               that version is already there.
  reinstall    Download and replace the binary, even if it is the same version.
  configure    Run the setup wizard (intergate config).
  setup-url    Print a new one-time link to the dashboard's setup, where the
               owner sets up email delivery and their account. It replaces
               the link given before.
  uninstall    Stop and remove the service and the binary. The configuration
               and data are kept unless --purge.
  client       Install or update intergate-tunnel, the client alone, to keep
               this machine's tunnels to a gate open, and open its wizard.
  uninstall-client
               Stop and remove intergate-tunnel and its service. Its
               configuration and key are kept unless --purge.
  help         Show this text.

With no command, the script asks which of these to do, offering the last ones
only when it finds intergate installed. With no terminal to ask on it installs.

Options:
  --dir DIR        Where the binary goes. Default: /usr/local/bin
                   (or INTERGATE_INSTALL_DIR)
  --version TAG    A release tag, such as v0.2.0. Default: the latest one.
                   (or INTERGATE_VERSION)
  --config FILE    The configuration file. Default: /etc/intergate/intergate.yaml
  --no-service     Do not offer to install or restart the systemd service.
  --purge          With uninstall: also delete the configuration, the data
                   directory (subdomains, keys, users) and the service user.
                   With uninstall-client: its configuration, key and user.
  -y, --yes        Do not ask: install the service, and delete with --purge.
  -h, --help       Show this text.

Environment:
  INTERGATE_DOWNLOAD_URL   A directory holding intergate-<os>-<arch>.tar.gz
                            (and intergate-tunnel-<os>-<arch>.tar.gz) and
                            SHA256SUMS, used instead of GitHub: a mirror, or
                            file:// for a build of your own.
EOF
}

say() { printf '%s\n' "$*"; }
warn() { printf 'intergate setup: warning: %s\n' "$*" >&2; }
die() {
	printf 'intergate setup: error: %s\n' "$*" >&2
	exit 1
}
need() { command -v "$1" >/dev/null 2>&1; }

# fetch URL FILE: false on any failure, a 404 included. With curl, or else
# wget, so `wget -qO- … | sh` works where curl is missing.
fetch() {
	if need curl; then
		curl -fsSL --retry 3 --connect-timeout 20 -o "$2" "$1"
	else
		wget -q --tries=3 --timeout=20 -O "$2" "$1"
	fi
}

# redirect URL: where URL redirects to, without following it.
redirect() {
	if need curl; then
		curl -fsSLI --retry 3 --connect-timeout 20 -o /dev/null -w '%{url_effective}' "$1"
	else
		wget -q -S --tries=3 --timeout=20 --max-redirect=0 -O /dev/null "$1" 2>&1 |
			sed -n 's/^ *Location: *//p' | tr -d '\r' | grep .
	fi
}

has_tty() { (: </dev/tty) 2>/dev/null; }

# as_root CMD...: run as root, through sudo when this is not root already.
as_root() {
	if [ "$(id -u)" = 0 ]; then
		"$@"
	elif need sudo; then
		sudo "$@"
	else
		die "this step needs root and sudo is not installed: run the script as root"
	fi
}

# maybe_root DIR CMD...: as root only when DIR is not writable as this user.
maybe_root() {
	d=$1
	shift
	while [ ! -d "$d" ]; do d=$(dirname "$d"); done
	if [ -w "$d" ]; then "$@"; else as_root "$@"; fi
}

# The release target this machine runs: the suffix of the asset's name.
detect_target() {
	os=$(uname -s)
	arch=$(uname -m)
	case "$os" in
	Linux) os=linux ;;
	Darwin) os=darwin ;;
	*) die "intergate is built for Linux and macOS, and this is $os" ;;
	esac
	case "$arch" in
	x86_64 | amd64) arch=amd64 ;;
	arm64 | aarch64) arch=arm64 ;;
	*) die "there is no intergate build for $arch: build it from source (https://github.com/$REPO)" ;;
	esac
	# A shell under Rosetta says x86_64 on Apple Silicon, and the native build
	# is the one worth running there.
	if [ "$os" = darwin ] && [ "$arch" = amd64 ] &&
		[ "$(sysctl -n sysctl.proc_translated 2>/dev/null || echo 0)" = 1 ]; then
		arch=arm64
	fi
	TARGET="$os-$arch"
}

# Sets TAG and BASE: which release, and where its files are. With
# INTERGATE_DOWNLOAD_URL there is no tag to ask GitHub about, and the version
# is whatever the downloaded binary says it is.
resolve_release() {
	if [ -n "${INTERGATE_DOWNLOAD_URL:-}" ]; then
		TAG=""
		BASE=${INTERGATE_DOWNLOAD_URL%/}
		return
	fi
	if [ -n "$VERSION" ]; then
		case "$VERSION" in
		v*) TAG=$VERSION ;;
		*) TAG=v$VERSION ;;
		esac
	else
		# The redirect GitHub answers `latest` with names the tag, and costs
		# none of the API's rate limit.
		latest=$(redirect "https://github.com/$REPO/releases/latest") ||
			die "could not reach GitHub to find the latest release"
		TAG=${latest##*/}
		case "$TAG" in
		v[0-9]*) ;;
		*) die "GitHub has no release of intergate to install yet" ;;
		esac
	fi
	BASE="https://github.com/$REPO/releases/download/$TAG"
}

# "0.2.0" for a intergate binary, or nothing.
version_of() {
	"$1" --version </dev/null 2>/dev/null | awk '{ print $2; exit }'
}

sha256() {
	if need sha256sum; then
		sha256sum "$1" | awk '{ print $1 }'
	elif need shasum; then
		shasum -a 256 "$1" | awk '{ print $1 }'
	elif need openssl; then
		openssl dgst -sha256 "$1" | awk '{ print $NF }'
	fi
}

# The sum the release publishes for an asset in its SHA256SUMS.
expected_sum() {
	fetch "$BASE/SHA256SUMS" "$TMP/SHA256SUMS" ||
		die "could not download $BASE/SHA256SUMS to check the download against"
	sum=$(awk -v f="$1" '$2 == f || $2 == "*" f { print $1; exit }' "$TMP/SHA256SUMS")
	[ -n "$sum" ] || die "$BASE/SHA256SUMS does not list $1"
	printf '%s\n' "$sum"
}

service_installed() { [ -f "$UNIT" ]; }
service_active() { need systemctl && systemctl is-active --quiet intergate 2>/dev/null; }
has_systemd() { [ "$(uname -s)" = Linux ] && [ -d /run/systemd/system ] && need systemctl; }

# Yes or no from a person; with nobody to ask, the default given.
ask() {
	question=$1
	default=$2
	if [ "$YES" = 1 ]; then return 0; fi
	if ! has_tty; then [ "$default" = y ]; return; fi
	if [ "$default" = y ]; then hint="[Y/n]"; else hint="[y/N]"; fi
	printf '%s %s ' "$question" "$hint" >/dev/tty
	read -r answer </dev/tty || answer=""
	[ -n "$answer" ] || answer=$default
	case "$answer" in
	[yY] | [yY][eE][sS]) return 0 ;;
	*) return 1 ;;
	esac
}

# Yes, from --yes or from a person. Never from the pipe the script came in on:
# with nobody to ask, the answer is no.
confirm() {
	if [ "$YES" = 1 ]; then return 0; fi
	has_tty || die "there is no terminal to ask on, so nothing was deleted: pass --yes"
	ask "$1" n
}

run_wizard() {
	has_tty || {
		say "To configure it, run: sudo $BIN config --config $CONFIG"
		return 1
	}
	say ""
	# The wizard writes the configuration where only root (and the service
	# user) can read it: it holds secrets.
	maybe_root "$(dirname "$CONFIG")" "$BIN" config --config "$CONFIG" </dev/tty >/dev/tty
}

# What follows a fresh install: configuration, then the service.
first_run() {
	if [ ! -f "$CONFIG" ]; then
		if ask "Create the configuration now with the setup wizard?" y && has_tty; then
			run_wizard || return 0
		else
			say ""
			say "Next, create the configuration with the setup wizard:"
			say "  sudo intergate config"
			return 0
		fi
	fi
	[ -f "$CONFIG" ] || return 0
	if [ "$SERVICE" = 1 ] && has_systemd && ! service_installed; then
		if ask "Run intergate as a system service, started at boot?" y; then
			as_root "$BIN" service --install --config "$CONFIG"
			return 0
		fi
	fi
	if ! service_installed; then
		say ""
		say "Start it with:"
		say "  sudo intergate start --detached     (sudo intergate stop to stop it)"
	fi
}

# After an update: the running service keeps the old binary until restarted.
restart_running() {
	if [ "$SERVICE" = 1 ] && service_active; then
		say "Restarting the intergate service..."
		as_root systemctl restart intergate
		say "The service runs $1 now."
	elif "$BIN" status --config "$CONFIG" >/dev/null 2>&1; then
		say "intergate is running: restart it to use $1:"
		say "  sudo intergate stop && sudo intergate start --detached"
	fi
}

already_installed() {
	say "intergate $1 is already installed at $BIN."
	say "To download it again: curl -fsSL $SETUP_URL | sh -s -- reinstall"
}

# fetch_release NAME: downloads NAME-<target>.tar.gz of the release,
# checks it against SHA256SUMS, unpacks it and runs it once. Sets NEW, the
# binary, and NEW_VERSION.
fetch_release() {
	[ -n "$TMP" ] || TMP=$(mktemp -d "${TMPDIR:-/tmp}/intergate-setup.XXXXXX")
	asset="$1-$TARGET.tar.gz"
	say "Downloading $1 ${TAG:+$TAG }for $TARGET..."
	if ! fetch "$BASE/$asset" "$TMP/$asset"; then
		die "could not download $BASE/$asset.
${TAG:+Release $TAG may have no build for $TARGET: see https://github.com/$REPO/releases/tag/$TAG
}To build it from source instead:
  go install github.com/$REPO/cmd/$1@latest"
	fi

	want=$(expected_sum "$asset")
	got=$(sha256 "$TMP/$asset")
	[ -n "$got" ] || die "no sha256sum, shasum or openssl here to check the download with"
	[ "$got" = "$want" ] || die "$asset does not match its checksum (expected $want, got $got)"

	tar -xzf "$TMP/$asset" -C "$TMP" || die "could not unpack $asset"
	NEW="$TMP/$1-$TARGET/$1"
	[ -f "$NEW" ] || die "$asset has no $1 binary in it"
	chmod 755 "$NEW"
	# Run before it replaces anything: a binary this system cannot run must
	# not take the place of one that works.
	if ! "$NEW" --version </dev/null >"$TMP/version" 2>"$TMP/error"; then
		die "the downloaded $1 does not run on this system:
$(cat "$TMP/error")"
	fi
	NEW_VERSION=$(awk '{ print $2; exit }' "$TMP/version")
}

# put_binary FILE NAME: installs FILE as $DIR/NAME.
put_binary() {
	maybe_root "$DIR" mkdir -p "$DIR" || die "could not create $DIR"
	# Copied beside the old one and renamed over it: nobody ever runs half a
	# binary, and a server already running keeps the file it started from.
	# shellcheck disable=SC2016 # $1..$4 are the inner shell's arguments
	if ! maybe_root "$DIR" sh -c 'cp "$1" "$2/.$4.$3" && mv -f "$2/.$4.$3" "$2/$4"' \
		sh "$1" "$DIR" "$$" "$2"; then
		maybe_root "$DIR" rm -f "$DIR/.$2.$$"
		die "could not write $DIR/$2"
	fi
}

install_intergate() {
	force=$1
	need curl || need wget || die "curl or wget is needed to download intergate"
	need tar || die "tar is needed to unpack intergate"
	detect_target
	resolve_release

	current=""
	if [ -x "$BIN" ]; then current=$(version_of "$BIN"); fi
	if [ "$force" = 0 ] && [ -n "$current" ] && [ "v$current" = "$TAG" ]; then
		already_installed "$current"
		first_run
		return
	fi

	fetch_release intergate
	new=$NEW
	version=$NEW_VERSION
	if [ "$force" = 0 ] && [ -n "$current" ] && [ "$current" = "$version" ]; then
		already_installed "$current"
		first_run
		return
	fi
	put_binary "$new" intergate

	if [ -z "$current" ]; then
		say "Installed intergate $version at $BIN."
		case ":${PATH:-}:" in
		*":$DIR:"*) ;;
		*) warn "$DIR is not on your PATH" ;;
		esac
		first_run
	elif [ "$current" = "$version" ]; then
		say "Reinstalled intergate $version at $BIN."
		restart_running "$version"
	else
		say "Updated intergate from $current to $version at $BIN."
		restart_running "$version"
	fi
}

configure_intergate() {
	[ -x "$BIN" ] || die "intergate is not installed in $DIR: install it first"
	run_wizard || exit 1
	if [ "$SERVICE" = 1 ] && service_active; then
		if ask "Restart the service to apply the settings?" y; then
			as_root systemctl restart intergate
		fi
	elif [ "$SERVICE" = 1 ] && has_systemd && ! service_installed && [ -f "$CONFIG" ]; then
		if ask "Run intergate as a system service, started at boot?" y; then
			as_root "$BIN" service --install --config "$CONFIG"
		fi
	fi
}

# The data directory named in the configuration, resolved against its
# directory as intergate does. Nothing when it can't be told.
data_dir() {
	[ -f "$CONFIG" ] || return 0
	if [ -r "$CONFIG" ]; then
		d=$(sed -n 's/^data_dir:[[:space:]]*//p' "$CONFIG")
	else
		d=$(as_root sed -n 's/^data_dir:[[:space:]]*//p' "$CONFIG")
	fi
	d=$(printf '%s\n' "$d" | sed 's/[[:space:]]*#.*$//; s/^["'\'']//; s/["'\'']$//' | head -n 1)
	[ -n "$d" ] || d=data
	case "$d" in
	/*) ;;
	*) d="$(dirname "$CONFIG")/$d" ;;
	esac
	case "$d" in
	*[!/]*) printf '%s\n' "${d%/}" ;;
	*) printf '/\n' ;; # only slashes: the root, which --purge refuses
	esac
}

# A new link to the dashboard's setup, from the running server. Only root
# and the service user may ask it.
setup_url() {
	[ -x "$BIN" ] || die "intergate is not installed in $DIR: install it first"
	maybe_root "$(dirname "$CONFIG")" "$BIN" setup-url --config "$CONFIG" || exit 1
}

uninstall_intergate() {
	if service_installed; then
		if [ -x "$BIN" ]; then
			as_root "$BIN" service --uninstall
		else
			as_root systemctl disable --now intergate || true
			as_root rm -f "$UNIT"
			as_root systemctl daemon-reload || true
		fi
	elif [ -x "$BIN" ] && "$BIN" status --config "$CONFIG" >/dev/null 2>&1; then
		maybe_root "$(dirname "$CONFIG")" "$BIN" stop --config "$CONFIG" || true
	fi

	if [ -e "$BIN" ] || [ -L "$BIN" ]; then
		maybe_root "$DIR" rm -f "$BIN" || die "could not remove $BIN"
		say "Removed $BIN."
	else
		say "intergate is not installed in $DIR."
	fi

	data=$(data_dir)
	if [ "$PURGE" = 0 ]; then
		if [ -f "$CONFIG" ] || { [ -n "$data" ] && [ -d "$data" ]; }; then
			say "Kept the configuration and data (subdomains, SSH keys, users):"
			[ ! -f "$CONFIG" ] || say "  $CONFIG"
			[ -z "$data" ] || [ ! -d "$data" ] || say "  $data"
			say "To delete them as well: curl -fsSL $SETUP_URL | sh -s -- uninstall --purge"
		fi
		return
	fi

	case "$data" in
	"" | / | "${HOME%/}" | /etc | /var | /var/lib | /usr | /usr/local)
		[ -z "$data" ] || die "the data directory is $data, which --purge will not delete"
		;;
	esac
	say "--purge deletes intergate's configuration and data: subdomains, SSH keys, users, certificates."
	[ ! -f "$CONFIG" ] || say "  $CONFIG"
	[ -z "$data" ] || [ ! -d "$data" ] || say "  $data ($(as_root du -sh "$data" 2>/dev/null | awk '{ print $1 }'))"
	if id intergate >/dev/null 2>&1; then say "  the intergate system user"; fi
	if ! confirm "Delete them?"; then
		say "Nothing deleted."
		return
	fi
	if [ -n "$data" ] && [ -d "$data" ]; then
		as_root rm -rf "$data" || die "could not delete $data"
		say "Deleted $data."
	fi
	if [ -f "$CONFIG" ]; then
		base=${CONFIG%.*}
		as_root rm -f "$CONFIG" "$base.env"
		say "Deleted $CONFIG."
		dir=$(dirname "$CONFIG")
		if [ "$(basename "$dir")" = intergate ]; then
			as_root rmdir "$dir" 2>/dev/null || true
		fi
	fi
	if id intergate >/dev/null 2>&1 && need userdel; then
		as_root userdel intergate 2>/dev/null && say "Deleted the intergate user."
	fi
}

# intergate-tunnel: the client alone, for a machine that keeps tunnels open
# to a gate. Its wizard sets up the tunnels and the service.
client_active() { need systemctl && [ -f "$CLIENT_UNIT" ] && systemctl is-active --quiet intergate-tunnel 2>/dev/null; }

# restart_client: a running client service starts the new binary.
restart_client() {
	if client_active; then
		as_root systemctl restart intergate-tunnel
	elif [ -f "$CLIENT_PLIST" ]; then
		as_root launchctl kickstart -k system/io.github.jgermade.intergate-tunnel
	else
		return 1
	fi
}

install_client() {
	need curl || need wget || die "curl or wget is needed to download intergate-tunnel"
	need tar || die "tar is needed to unpack intergate-tunnel"
	detect_target
	resolve_release
	current=""
	if [ -x "$CBIN" ]; then current=$(version_of "$CBIN"); fi
	if [ -n "$current" ] && [ "v$current" = "$TAG" ]; then
		say "intergate-tunnel $current is already installed at $CBIN."
	else
		fetch_release intergate-tunnel
		if [ -n "$current" ] && [ "$current" = "$NEW_VERSION" ]; then
			say "intergate-tunnel $current is already installed at $CBIN."
		else
			put_binary "$NEW" intergate-tunnel
			if [ -z "$current" ]; then
				say "Installed intergate-tunnel $NEW_VERSION at $CBIN."
			else
				say "Updated intergate-tunnel from $current to $NEW_VERSION at $CBIN."
				if restart_client; then
					say "The intergate-tunnel service runs $NEW_VERSION now."
				fi
			fi
		fi
	fi
	if has_tty; then
		say ""
		as_root "$CBIN" setup </dev/tty >/dev/tty
	else
		say ""
		say "Next, set up this machine's tunnels:"
		say "  sudo intergate-tunnel setup"
		say "or, for one: sudo intergate-tunnel add web1.gate.example.com --http 8080"
	fi
}

uninstall_client() {
	if [ -f "$CLIENT_UNIT" ] || [ -f "$CLIENT_PLIST" ]; then
		if [ -x "$CBIN" ]; then
			as_root "$CBIN" uninstall
		elif [ -f "$CLIENT_UNIT" ]; then
			as_root systemctl disable --now intergate-tunnel || true
			as_root rm -f "$CLIENT_UNIT"
			as_root systemctl daemon-reload || true
		else
			as_root launchctl bootout system/io.github.jgermade.intergate-tunnel || true
			as_root rm -f "$CLIENT_PLIST"
		fi
	fi
	if [ -e "$CBIN" ] || [ -L "$CBIN" ]; then
		maybe_root "$DIR" rm -f "$CBIN" || die "could not remove $CBIN"
		say "Removed $CBIN."
	else
		say "intergate-tunnel is not installed in $DIR."
	fi
	if [ "$PURGE" = 0 ]; then
		if [ -d "$CLIENT_CONFIG_DIR" ]; then
			say "Kept its tunnels and this machine's key: $CLIENT_CONFIG_DIR"
			say "To delete them as well: curl -fsSL $SETUP_URL | sh -s -- uninstall-client --purge"
		fi
		return
	fi
	say "--purge deletes this machine's tunnels and its key: $CLIENT_CONFIG_DIR"
	if ! confirm "Delete them?"; then
		say "Nothing deleted."
		return
	fi
	if [ -d "$CLIENT_CONFIG_DIR" ]; then
		as_root rm -rf "$CLIENT_CONFIG_DIR" || die "could not delete $CLIENT_CONFIG_DIR"
		say "Deleted $CLIENT_CONFIG_DIR."
	fi
	if id intergate-tunnel >/dev/null 2>&1 && need userdel; then
		as_root userdel intergate-tunnel 2>/dev/null && say "Deleted the intergate-tunnel user."
	fi
}

# No command was typed: ask what to do, offering the other options only when
# intergate is installed. The answer becomes COMMAND.
choose_command() {
	if ! has_tty; then
		say "There is no terminal to ask on, so: install. (--help for the commands.)"
		COMMAND=install
		return
	fi
	current=""
	if [ -x "$BIN" ]; then current=$(version_of "$BIN"); fi
	# The options, numbered as they are shown: OPTION_<n> is the command.
	n=0
	option() {
		n=$((n + 1))
		eval "OPTION_$n=\$1"
		say "  $n) $2"
	}
	if [ -n "$current" ]; then
		state=""
		running=0
		if service_active; then
			state=" — running as a service"
			running=1
		elif "$BIN" status --config "$CONFIG" >/dev/null 2>&1; then
			running=1
		fi
		say "intergate $current is installed at $BIN$state."
		say ""
		option install "Update to the latest release"
		option reinstall "Reinstall $current"
		option configure "Configure: subdomains, SSH keys, users and settings"
		if [ "$running" = 1 ]; then
			option setup-url "New link to the dashboard's setup: email delivery and the owner"
		fi
		option uninstall "Uninstall — keeps the configuration and data"
	fi
	ccurrent=""
	if [ -x "$CBIN" ]; then ccurrent=$(version_of "$CBIN"); fi
	if [ -z "$current" ]; then
		if [ -n "$ccurrent" ]; then
			say "intergate-tunnel $ccurrent is installed at $CBIN."
		else
			say "intergate opens a gate from your machine to the web: an encrypted"
			say "SSH tunnel per subdomain, managed from a web dashboard."
		fi
		say ""
		option install "Install the server: a gate for your domain"
	fi
	if [ -n "$ccurrent" ]; then
		option client "Set up this machine's tunnels (and update intergate-tunnel)"
		option uninstall-client "Uninstall intergate-tunnel — keeps its tunnels and key"
	else
		option client "Connect this machine to a gate: keep its tunnels open (intergate-tunnel)"
	fi
	option quit "Quit"
	while :; do
		printf 'What should this do? [1] ' >/dev/tty
		read -r answer </dev/tty || answer=1
		[ -n "$answer" ] || answer=1
		case "$answer" in
		q | Q) COMMAND=quit ;;
		*[!0-9]*) COMMAND="" ;;
		*) eval "COMMAND=\${OPTION_$answer:-}" ;;
		esac
		case "$COMMAND" in
		quit)
			say "Nothing to do."
			exit 0
			;;
		"") warn "not an option" ;;
		*) return ;;
		esac
	done
}

main() {
	COMMAND=install
	EXPLICIT=0
	DIR=${INTERGATE_INSTALL_DIR:-}
	VERSION=${INTERGATE_VERSION:-}
	CONFIG=/etc/intergate/intergate.yaml
	SERVICE=1
	PURGE=0
	YES=0
	while [ $# -gt 0 ]; do
		case "$1" in
		install | reinstall | configure | uninstall | setup-url | client | uninstall-client)
			COMMAND=$1
			EXPLICIT=1
			;;
		update) # what install does when there is something newer
			COMMAND=install
			EXPLICIT=1
			;;
		help | -h | --help)
			usage
			return
			;;
		--dir)
			[ $# -ge 2 ] || die "--dir needs a directory"
			DIR=$2
			shift
			;;
		--dir=*) DIR=${1#*=} ;;
		--version)
			[ $# -ge 2 ] || die "--version needs a tag, such as v0.2.0"
			VERSION=$2
			shift
			;;
		--version=*) VERSION=${1#*=} ;;
		--config)
			[ $# -ge 2 ] || die "--config needs a file"
			CONFIG=$2
			shift
			;;
		--config=*) CONFIG=${1#*=} ;;
		--no-service) SERVICE=0 ;;
		--purge) PURGE=1 ;;
		-y | --yes) YES=1 ;;
		*) die "unknown argument: $1 (see --help)" ;;
		esac
		shift
	done

	if [ "$PURGE" = 1 ] && [ "$COMMAND" != uninstall ] && [ "$COMMAND" != uninstall-client ]; then
		die "--purge goes with uninstall or uninstall-client"
	fi
	[ -n "$DIR" ] || DIR=/usr/local/bin
	# A `--dir=~/bin` reaches here unexpanded: the shell expands a tilde after
	# `=` only in an assignment.
	# shellcheck disable=SC2088
	case "$DIR" in
	"~") DIR=$HOME ;;
	"~/"*) DIR="$HOME/${DIR#"~/"}" ;;
	/*) ;;
	*) DIR="$(pwd)/$DIR" ;;
	esac
	DIR=${DIR%/}
	BIN="$DIR/intergate"
	CBIN="$DIR/intergate-tunnel"
	case "$CONFIG" in
	/*) ;;
	*) CONFIG="$(pwd)/$CONFIG" ;;
	esac
	if [ "$EXPLICIT" = 0 ]; then choose_command; fi

	trap '[ -z "$TMP" ] || rm -rf "$TMP"' EXIT
	trap 'exit 130' INT
	trap 'exit 143' TERM

	case "$COMMAND" in
	install) install_intergate 0 ;;
	reinstall) install_intergate 1 ;;
	configure) configure_intergate ;;
	setup-url) setup_url ;;
	uninstall) uninstall_intergate ;;
	client) install_client ;;
	uninstall-client) uninstall_client ;;
	esac
}

main "$@"
