#!/bin/bash

argc=$#
argv=("$@")
__dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# source echo2ui util
. ${__dir}/echo2ui_utils --source-only

display_usage()
 { 
   bordered_title "launcher for echo2ui by keshavnrj@gmail.com"
   echo -e "\nthis wrapper script will launch the application and bind it to echo2ui\n" 
   echo -e "\nUsage: $0 [launchable-app or its path] [path to log file](optional)\n" 
   echo -e "Example 1: $0 wonderwall\n"
   echo -e "Example 2: $0 wonderwall /tmp/wonderwall.log\n"
 }
 
 # check whether user had supplied -h or --help . If yes display usage 
 if [[ ( $* == "--help") ||  $* == "-h" ]] 
 then 
   display_usage
   exit 0
 fi 
 
 # if less than 2 arguments supplied, display usage 
 if [[ $* != "--help" || $* != "-h" ]] && [ $# -le 0 ]; 
 then 
   echo -e "\nError: insufficient arguments passed \n" 
   display_usage
   exit 1
 fi

# path to log file where we want to stdout and stderr on error
LOG_FILE="$2";

# save stdout & stderr of sub shell to output,
# while piping to parent tty
# keeping the exitcode intact
output="$(
    # exit sub shell with non zero exit 
    set -e; 
    {
       bash -c "$1" 2>&1 | tee /dev/tty; exit ${PIPESTATUS[0]}
    };
)";

# get sub shell exit code
# save error if any
# exit with error code if any
# or exit 0;
ec="$?"; if [ $ec -eq 0 ]; then 
    # zero exit code
    
    exit 0; 
else
    # non zero exit code

    #echo $output;
    
    # if path to it was provided
    if [ -n "$LOG_FILE" ]; then
        NOW=$( date )
        echo -e "$NOW: $output\n" >> "$LOG_FILE";
    fi;
    
    # chop the output to show only last 10 lines
    coutput=""
    if [ -n "$LOG_FILE" ]; then
       coutput+="Complete log stored in: "$LOG_FILE"\n"
       coutput+=$(repeated_char 70 "_")
       coutput+="\n\n"
    fi
    linescount=$(echo "$output" | wc -l)

    if [ $linescount -gt 10 ]; then
       coutput+="the output was chopped to 10 lines\n"
       coutput+=$(repeated_char 70 "_")
       coutput+="\n\n"
    fi
    coutput+=$(echo "$output" | tail -n10)
    coutput+="\n\n"
    coutput+=$(repeated_char 70 "_")
    coutput+="\n\nExit code: $ec"
    
    # call echo2ui to output the error message
    ${__dir}/echo2ui "Context" "Title" "$coutput" 80 26 > /dev/null 2>&1

    # exit with sub shell exit code
    exit "$ec"; 
fi;
