#!/bin/sh
set -eu
SERVER="connect.t.foobox.app:443"
BASE="https://get.foobox.app"
PROTO="http"; NAME=""; PORT=""; TOKEN=""
while [ $# -gt 0 ]; do
  case "$1" in
    --token) TOKEN="$2"; shift 2 ;;
    --name) NAME="$2"; shift 2 ;;
    --port) PORT="$2"; shift 2 ;;
    --proto) PROTO="$2"; shift 2 ;;
    --server) SERVER="$2"; shift 2 ;;
    *) echo "unknown arg: $1" >&2; exit 2 ;;
  esac
done
[ -n "$TOKEN" ] || { echo "missing --token" >&2; exit 2; }
[ -n "$PORT" ] || { echo "missing --port" >&2; exit 2; }
[ "$PROTO" = "tcp" ] || [ -n "$NAME" ] || { echo "http needs --name (subdomain)" >&2; exit 2; }

os=$(uname -s); machine=$(uname -m)
case "$os" in
  Linux) OS=linux ;;
  Darwin) OS=darwin ;;
  *) echo "unsupported OS: $os" >&2; exit 1 ;;
esac
case "$machine" in
  x86_64|amd64) ARCH=amd64 ;;
  aarch64|arm64) ARCH=arm64 ;;
  armv7l|armv6l|arm) ARCH=arm ;;
  *) echo "unsupported arch: $machine" >&2; exit 1 ;;
esac
if [ "$OS" = "darwin" ] && [ "$ARCH" = "arm" ]; then
  echo "unsupported: 32-bit ARM macOS" >&2; exit 1
fi

BIN=/usr/local/bin/tunnel
echo "downloading $BASE/bin/tunnel-$OS-$ARCH -> $BIN"
if command -v curl >/dev/null 2>&1; then
  curl -fsSL "$BASE/bin/tunnel-$OS-$ARCH" -o "$BIN"
else
  wget -qO "$BIN" "$BASE/bin/tunnel-$OS-$ARCH"
fi
chmod +x "$BIN"

set -- service install "$PROTO" "$PORT" --server "$SERVER" --token "$TOKEN"
if [ "$PROTO" = "http" ]; then
  set -- "$@" --subdomain "$NAME"
elif [ -n "$NAME" ]; then
  set -- "$@" --remote-port "$NAME"
fi
"$BIN" "$@"
echo "done. manage with: $BIN service status | uninstall"
