#!/bin/sh

run_command() {

  #############################################################################
  ## This function exists for two reasons; 1) to give better feedback to the ##
  ## user and 2) provide a rudimentary form of error checking to just bail   ##
  ## out if things go south.                                                 ##
  ##                                                                         ##
  ## Two important things to know about it.                                  ##
  ## - Always remember to begin and end the command you want to have run     ##
  ## with quotation marks to have it passed through as just one long string. ##
  ## - Any quotation marks inside the command have to be commented out by    ##
  ## prefixing with a backslash so that they pass through "echo" as literal  ##
  ## quotes. Example:                                                        ##
  ## run_command "echo \"\""                                                 ##
  ## To pass through those same characters but literally(\"):                ##
  ## run_command "echo \\\"\\\""                                             ##
  #############################################################################

  RUN_DIR="/var/tmp"
  if [ ! -d ${RUN_DIR} ]; then
    mkdir ${RUN_DIR}
    chown root:$(id root | awk '{gsub(/\(/, " "); gsub(/\)/, " "); if ($3 ~ "gid") print $4}') ${RUN_DIR}
    chmod 777 ${RUN_DIR}
  fi
  COMMAND=$(mktemp ${RUN_DIR}/run_command.cmd.XXXXXX)
  OUTPUT=$(mktemp ${RUN_DIR}/run_command.out.XXXXXX)
  echo "#!/bin/sh" > ${COMMAND}
  echo "$*" >> ${COMMAND}
  chmod +x ${COMMAND}
  echo "+-- Running command:"
  echo "$(cat ${COMMAND} | egrep -v "^#!/bin/sh$")"
  ${COMMAND} > ${OUTPUT} 2>&1
  echo "+-- Output was:"
  cat ${OUTPUT}
  if [ $? -gt "0" ]; then
    echo "+-- Command Failed!"
    echo "+-- Output was:"
    cat ${OUTPUT}
    echo ""
    rm ${OUTPUT} > /dev/null 2>&1
    rm ${COMMAND} > /dev/null 2>&1
    exit 1
  else
    echo "+-- Command succeeded."
    echo ""
  fi
  rm ${OUTPUT} > /dev/null 2>&1
  rm ${COMMAND} > /dev/null 2>&1
}

run_command "echo \"\\\\\""
