#!/bin/sh
#
# $Id: script2log,v 1.5 2015/02/04 23:51:01 tom Exp $
# filter "most" escape sequences from files such as typescript's.
#
# for demonstration purposes (and because it is likely to be omitted from
# some BSD platforms), this does not use getopts.

if test $# != 0; then
  output=
  # shellcheck disable=SC2249
  case "x$1" in
    x-o)
      shift 1
      if test "$#" = 0; then
        echo "?? expected parameter after -o" >&2
        exit 1
      fi
      output="$1"
      shift 1
      ;;
    x-o*)
      output=$(echo "x$1" | sed -e 's/^...//')
      shift 1
      ;;
  esac
  if test -n "${output}"; then
    # shellcheck disable=SC2048,SC2086
    exec "$0" $* >"${output}"
  fi
fi

# ensure POSIX locale
unset LANG
unset LANGUAGE
unset LC_ALL
unset LC_CTYPE
if test "$#" != 0; then
  # shellcheck disable=SC2048,SC2086
  for input in $*; do
    test -f "${input}" || continue
    case "${input}" in
      *.gz)
        gzip -dc "${input}" | "$0"
        ;;
      *.bz2)
        bzip2 -dc "${input}" | "$0"
        ;;
      *)
        "$0" <"${input}"
        ;;
    esac
  done
elif test -f "$0.sed"; then
  # The separate script is more portable than the command-line arguments,
  # because of the loop construct.  Unix and BSDs do not support that
  # as a single line.  Other than changing it to a series of lines, the
  # two scripts are equivalent.
  sed -f "$0.sed"
else
  # Trim ordinary ANSI sequences, then OSC sequences, then backspace
  # sequences, then trailing CR's and finally overstruck sections of
  # lines.
  #
  # There are still several interesting cases which cannot be handled
  # with a script of this sort.  For example:
  #       CSI K (clear line)
  #       cursor movement within the line
  sed \
    -e 's/^[[[][<=>?]\{0,1\}[;0-9]*[@-~]//g' \
    -e 's/^[[]][^^[]*^G//g' \
    -e 's/^[[]][^^[]*^[\\//g' \
    -e ':loop; s/[^^H]^H\(.\)/\1/g; t loop;' \
    -e 's/^M^M*$//g' \
    -e 's/^.*^M//g' \
    -e 's/^[[^[]//g'
fi
