The main tool they use is a system called a 'Package Manager'. Package managers know about how different programs interact. Take the example of installing a working email server. The package manager will check for Internet connectivity before installing the mail program. If the necessary software to do this is not installed it will automatically install it or stop with an error.
Package managers know about how to install most programs that are available.
The people writing the package add this information. They examine the program and bundle extra information and even set up scripts with it. The package manager then uses this extra information to do its automatic install magic.