#!/bin/sh

#  Copyright (c) 2018, Avi Halachmi (:avih) https://github.com/avih/shcmp
#
#  Permission to use, copy, modify, and/or distribute this software for any
#  purpose with or without fee is hereby granted, provided that the above
#  copyright notice and this permission notice appear in all copies.
#
#  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
#  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
#  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
#  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
#  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
#  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
#  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

if false; then
  # (old) hush: can't parse "subshell function" e.g. -c 'f() (true)'

  # (old) hush: aborts prematurely on -c 'set -e; false || x=1; echo OK'
  # bosh: aborts prematurely on -c 'set -e; f() { false; }; while f; do :; done; echo OK'
  set -e

  # posh: aborts prematurely on -c 'set -u; echo "$@"; echo OK'
  set -u 2>/dev/null || :

  #set -x
fi

# Quote the args for shell re-input. E.g. a=$(SHQ "$@"); eval printf =%s= "$a"
# The output should be eval'ed quoted, else [runs of] IFS will turn to space.
# Note: might touch some variables if not used in a subshell
SHQ() {
  out=
  for v; do
    out=$out\'
    while case $v in *\'*) : ;; *) false ;; esac do
      out=$out${v%%\'*}"'\''"
      v=${v#*\'}
    done
    out=$out$v"' "
  done
  printf %s "${out%?}"
}

# ~/.shcmprc can override these functions, which are called at the same context
shcmp_time_init() {
  TIME_PRINT=${TIME_PRINT-0}
  . "${SHCMP_TIME_FILE-time.sh}"
}
shcmp_time_switch_to() { time_switch_to "$1"; }
shcmp_time_finish() { time_finish; }

# $1: IFS-separated COMMANDS, $2: TRAIL [,$3..: ARG...]
# Run each of COMMANDS with ARG... (quoted) and TRAIL (unquoted),
# and cluster them by (std) output + exit code.
# Once done, prints (shell) quoted pairs of args: [<cmds1> <out1> [..]]
# Note: COMMANDS can be functions, commands, etc.
# Note: might touch some variables if not used in a subshell
cluster_outputs() {
  CMDS=$1
  TRAIL=$2
  shift 2
  ARGS=$(SHQ "$@")
  set --
  [ -z "$DOTIME" ] || shcmp_time_init $CMDS

  for C in $CMDS; do
    [ -z "$DOTIME" ] || shcmp_time_switch_to "$C"

    OUT=$( (eval "$C $ARGS $TRAIL") && echo "(exit:0)" || echo "(exit:$?)")

    # add "$C" to an existing pair (in "$@") or add a new pair "$C" "$OUT"
    I=1
    PA=
    FOUND=
    while [ $I -lt $# ]; do
      J=$((I + 1))
      eval JV=\${$J}
      [ "$JV" = "$OUT" ] && PA=$PA' "${'$I'} $C" "${'$J'}"' && FOUND=1 \
        || PA=$PA' "${'$I'}"    "${'$J'}"'
      I=$((I + 2))
    done
    [ "$FOUND" ] && eval set -- $PA || set -- "$@" "$C" "$OUT"
  done

  [ -z "$DOTIME" ] || shcmp_time_finish
  SHQ "$@"
}

# output format utils

list_items() {
  printf %s "$*" | sed 's/ /, /g'
}

# args: 1/0 to trim/not-trim output, then arg pairs of: cmd-list common-output
# Note: might touch some variables if not used in a subshell
fmt_out() {
  while [ $# -gt 0 ]; do
    printf "= %s:\n%s\n" "$(list_items $1)" "$2"
    shift 2
    [ $# = 0 ] || echo
  done
}

# main

# setup the tested shells
RC=~/.shcmprc # no tilde expansion in hush at this time, so try also $HOME
[ -e "$RC" ] || RC="$HOME"/.shcmprc

[ -e "$RC" ] && . "$RC" \
  || {
    # built in sample shells - if ~/.shcmprc doesn't exist or has non-0 exit
    busybox_ash() { busybox ash "$@"; }
    busybox_hush() { busybox hush "$@"; }
    bash_posix() { bash --posix "$@"; }
    mksh_posix() { mksh -o posix "$@"; }
    yash_posix() { yash -o posixlycorrect "$@"; }
    foo_shell() { /path/to/whatever "$@"; }

    shells="sh bash bash_posix busybox_ash busybox_hush dash mksh mksh_posix
            ksh ksh93 pdksh mrsh loksh oksh bosh pbosh posh yash yash_posix"

    working_shells= # keep only the shells that exist/work on this system
    for s in $shells; do
      if $s -c ":" 2>/dev/null; then
        working_shells="$working_shells $s"
      fi
    done
    shells=$working_shells
  }

REDIRECT='2>&1' ALLOW_EMPTY= DOTIME=
while true; do
  case ${1-} in
    --SHELL)
      shift
      ("$@")
      exit
      ;;
    --NOERR)
      REDIRECT=
      shift
      ;;
    --TIME)
      DOTIME=1
      shift
      ;;
    --help | -h)
      printf %s\\n "Usage: ${0##*/} -h|--help | [--NOERR] [--TIME] arg..."
      printf %s\\n "       ${0##*/} --SHELL shell [arg...]"
      printf \\n
      printf %s\\n "Run different shells with arg... and cluster by output + exit-code."
      printf %s\\n "Succeeds only when all shells behave the same (one cluster)."
      printf %s\\n "Note: any unrecognized option, e.g. -c, is considered the begining of arg."
      printf \\n
      printf %s\\n "  --NOERR  Capture and cluster by stdout only, else (default) stdout+stderr."
      printf %s\\n "  --TIME   Measure durations - expects \$SHCMP_TIME_FILE or time.sh at \$PATH ."
      printf %s\\n "           See https://github.com/avih/time.sh ."
      printf %s\\n "  --SHELL  Run ${0##*/}-name \`shell' [arg...] without processing or redirections."
      printf \\n
      printf %s\\n "Home: https://github.com/avih/shcmp"
      exit 0
      ;;
    --)
      ALLOW_EMPTY=1
      shift
      break
      ;;
    *) break ;;
  esac
done

[ $# -gt 0 ] || [ "$ALLOW_EMPTY" ] \
  || {
    >&2 printf %s\\n "${0##*/}: missing arg. Add \`--' to force. See usage with -h"
    exit 2
  }

eval "set -- $(cluster_outputs "$shells" "$REDIRECT" "$@")"
fmt_out "$@"
[ "$#" = 2 ] || exit 1
