1# Log TCP output.
2#
3# Argument:  Output filename.
4#
5# Options:
6#   -a    Append.  Otherwise the existing file is truncated without warning.
7#	  (N.B.: even if logging was already active to it!)
8#   -s    Per-session logs.  Output to <filename>1, <filename>2, etc.
9#   -c    Close logging.
10#   -n/-N Turn off or on normal output; output only goes to the logfile, if
11#         any.  Otherwise, output also appears interactively.  This
12#         can be given with -c (or any other option), then no output
13#         goes anywhere.  However, input is still handled by the usual
14#         mechanisms --- $tcp_lines and $TCP_LINE are still set, hence
15#         tcp_expect still works.  Equivalent to (un)setting TCP_SILENT.
16#
17# With no options and no arguments, print the current configuration.
18#
19# Per-session logs are raw output, otherwise $TCP_PROMPT is prepended
20# to each line.
21
22emulate -L zsh
23setopt cbases extendedglob
24
25local opt append sess close
26integer activity
27while getopts "ascnN" opt; do
28  (( activity++ ))
29  case $opt in
30    # append to existing file
31    a) append=1
32       ;;
33    # per-session
34    s) sess=1
35       ;;
36    # close
37    c) close=1
38       ;;
39    # turn off interactive output
40    n) TCP_SILENT=1
41       ;;
42    # turn on interactive output
43    N) unset TCP_SILENT
44       ;;
45    # incorrect option
46    \?) return 1
47	;;
48    # correct option I forgot about
49    *) print "$0: option -$opt not handled, oops." >&2
50       return 1
51       ;;
52  esac
53done
54(( OPTIND > 1 )) && shift $(( OPTIND - 1))
55
56if [[ -n $close ]]; then
57  if (( $# )); then
58    print "$0: too many arguments for -c" >&2
59    return 1
60  fi
61  unset TCP_LOG TCP_LOG_SESS
62  return 0
63fi
64
65if (( $# == 0 && ! activity )); then
66  print "\
67Per-session log: ${TCP_LOG_SESS:-<none>}
68Overall log:     ${TCP_LOG:-<none>}
69Silent?          ${${TCP_SILENT:+yes}:-no}"
70  return 0
71fi
72
73if (( $# != 1 )); then
74  print "$0: wrong number of arguments" >&2
75  return 1
76fi
77
78if [[ -n $sess ]]; then
79  typeset -g TCP_LOG_SESS=$1
80  if [[ -z $append ]]; then
81    local sesslogs
82    integer i
83    sesslogs=(${TCP_LOG_SESS}*(N))
84    # yes, i know i can do this with multios
85    for (( i = 1; i <= $#sesslogs; i++ )); do
86      : >$sesslogs[$i]
87    done
88  fi
89else
90  typeset -g TCP_LOG=$1
91  [[ -z $append ]] && : >$TCP_LOG
92fi
93
94return 0
95