#!/usr/bin/env bash

source "${DOTFILES}/scripts/core/main.sh"

##? Trick an application into thinking its stdout is a terminal intead of a pipe
##?
##? Extracted from https://stackoverflow.com/questions/1401002/how-to-trick-an-application-into-thinking-its-stdout-is-a-terminal-not-a-pipe/60279429#60279429
##?
##? Usage:
##?     faketty <commands...>
##?
##? Examples:
##?     faketty ls --color=auto | cat

doc::maybe_help "$@"

faketty() {
   # Create a temporary file for storing the status code
   tmp=$(mktemp)

   # Ensure it worked or fail with status 99
   [ "$tmp" ] || return 99

   # Produce a script that runs the command provided to faketty as
   # arguments and stores the status code in the temporary file
   cmd="$(printf '%q ' "$@")"'; echo $? > '$tmp

   # Run the script through /bin/sh with fake tty
   if [ "$(uname)" = "Darwin" ]; then
      # MacOS
      script -Fq /dev/null /bin/sh -c "$cmd"
   else
      script -qfc "/bin/sh -c $(printf "%q " "$cmd")" /dev/null
   fi

   # Ensure that the status code was written to the temporary file or
   # fail with status 99
   [ -s "$tmp" ] || return 99

   # Collect the status code from the temporary file
   err=$(cat "$tmp")

   # Remove the temporary file
   rm -f "$tmp"

   # Return the status code
   return "$err"
}

faketty "$@"
