execute() {
  cmds="$1"
  msg="${2:-$1}"
  tmpfile="$(mktemp /tmp/XXXXXX)"
  ret=0
  cmdspid=""
  # if the current process is ended, also end all its subprocesses.
  set_trap "EXIT" "kill_all_subprocesses"
  # execute commands in background
  # shellcheck disable=SC2261
  eval "${cmds}" \
    >/dev/null 2>&1 \
    2> "${tmpfile}" &
  cmdspid=$!
  # show a spinner if the commands require more time to complete.
  spinner "${cmdspid}" "${cmds}" "${msg}"
  # wait for the commands to no longer be executing in the background,
  # and then get their exit code.
  wait "${cmdspid}" >/dev/null 2>&1
  ret=$?
  # print output based on what happened.
  print_result "${ret}" "${msg}"
  if [ "${ret}" -ne 0 ]; then
    print_error_stream < "${tmpfile}"
  fi
  rm -rf "${tmpfile}"
  return "${ret}"
}

print_result() {
  if [ "$1" -eq 0 ]; then
    print_success "$2"
  else
    print_error "$2"
  fi
  return "$1"
}

print_in_color() {
  # shellcheck disable=SC2312
  printf '%b' "$(tput setaf "$2" 2>/dev/null)" "$1" "$(tput sgr0 2>/dev/null)"
}

print_in_green() {
  print_in_color "$1" 2
}

print_in_red() {
  print_in_color "$1" 1
}

print_error() {
  print_in_red "   [✖] $1 $2\n"
}

print_success() {
  print_in_green "   [✔] $1\n"
}
