#!/bin/sh
set -eu

BASE_URL="${TINK_BASE_URL:-https://meet.tink.bot}"

if [ -z "${HOME:-}" ] || [ ! -d "$HOME" ] || [ ! -w "$HOME" ]; then
  echo "Tink needs a writable home directory. Set HOME to a writable directory, then run the Tink install command again."
  exit 1
fi

INSTALL_ROOT="$HOME/.tink"
BIN_DIR="$HOME/.local/bin"
AGENT_URL="$BASE_URL/releases/tink.js"

if ! command -v curl >/dev/null 2>&1; then
  echo "curl is required to install tink. See https://tink.bot/docs#install-prerequisites for prerequisite guidance."
  exit 1
fi

if ! command -v node >/dev/null 2>&1; then
  echo "Tink requires Node.js 20 or newer on the target machine."
  echo "Install Node.js from https://nodejs.org/en/download, then run the Tink install command again."
  exit 1
fi

NODE_MAJOR="$(node -p "process.versions.node.split('.')[0]")"
if [ "$NODE_MAJOR" -lt 20 ]; then
  echo "Tink requires Node.js 20 or newer (found Node.js $NODE_MAJOR)."
  echo "Upgrade Node.js from https://nodejs.org/en/download, then run the Tink install command again."
  exit 1
fi

mkdir -p "$INSTALL_ROOT/bin" "$BIN_DIR"
curl -fsSL "$AGENT_URL" -o "$INSTALL_ROOT/bin/tink.js"
chmod 755 "$INSTALL_ROOT/bin/tink.js"

cat > "$BIN_DIR/tink" <<'EOF'
#!/bin/sh
exec node "$HOME/.tink/bin/tink.js" "$@"
EOF
chmod 755 "$BIN_DIR/tink"

case ":$PATH:" in
  *":$BIN_DIR:"*) ;;
  *) echo "Add $BIN_DIR to PATH to use tink directly." ;;
esac

echo "tink installed to $BIN_DIR/tink"
exec "$BIN_DIR/tink" onboard --api-base "$BASE_URL"
