#!/bin/sh

#
# Copyright (c) 1994 Open Software Foundation, Inc.
# 
# Permission is hereby granted to use, copy, modify and freely distribute
# the software in this file and its documentation for any purpose without
# fee, provided that the above copyright notice appears in all copies, and
# that both the copyright notice and this permission notice appear in
# supporting documentation.  Further, provided that the name of Open
# Software Foundation, Inc. ("OSF") not be used in advertising or
# publicity pertaining to distribution of the software without prior
# written permission from OSF.  OSF makes no representations about the
# suitability of this software for any purpose.  It is provided "AS IS"
# without express or implied warranty.
#

#############################################
#  Setup environment and program variables  #
#############################################
#  if your platform is missing the
#  uname commane, comment out the
#  case statement and add the correct
#  definition for OTPATH.  So far, I've
#  only seen this with next machines
#
case `uname -s`_`uname -m` in
   OSF1_i386)       OTPATH=/project/tools/bin/i386        ;;
   OSF1_mips)       OTPATH=/project/tools/bin/mips.ULTRIX ;;
   HP-UX_9000/7*)   OTPATH=/project/tools/bin/HP          ;;
   ULTRIX_RISC)     OTPATH=/project/tools/bin/mips.ULTRIX ;;
   SunOS_sun4*)     OTPATH=/project/tools/bin/sparc       ;;
   *)               OTPATH=/usr/local/bin                 ;;
esac
if [ "d$EDITOR" = "d" ]; then
   [ -r /usr/bin/emacs ] && EDITOR=/usr/bin/emacs
   [ -r /usr/local/bin/emacs ] && EDITOR=/usr/local/bin/emacs
   export EDITOR
fi
PROGRAM=`basename $0`
REPORT=""

#####################################################
#  Mount ot resources if they aren't already there  #
#####################################################
[ -r /project/ot/hotline/hotline.def ] || /usr/local/bin/osfmount ot hotline 
[ "$OTPATH" = /usr/local/bin ] || [ -r /project/tools/bin  ] ||\
             /usr/local/bin/osfmount tools
if [ ! -r $OTPATH/ot -o ! -r /project/ot/hotline/hotline.def ]; then
   echo Could not mount the correct ot resources.
   exit 1
fi

########################
#  Main parsing block  #
########################
case $# in

   ### No Arguments to Hotline ###
   '0') $OTPATH/ot -photline -e ;;

   ### One Argument to Hotline ###
   '1') case $1 in
        [0-9]|[0-9][0-9]|[0-9][0-9][0-9]|[0-9][0-9][0-9][0-9]|\
        [0-9][0-9][0-9][0-9][0-9]|[0-9][0-9][0-9][0-9][0-9][0-9])
               $OTPATH/ot -photline -u -n$1 ;;
        /*tmp/*)  ed $1 <<END >/dev/null      # Called when 'hotline -phone <sender>' happens (see below)
/^Reported by/s/:.*\$/: $HOT_SENDER/
/^Method/s/:.*\$/: phone/
w
q
END
                                              # Edit some fields to make template a phone template
               $HOT_EDITOR $1 ;;              # Call users prefered editor, then back to OT, then below
	'-e')  $OTPATH/ot_bugs -photline ;;
        '-'[oO])
               if [ $1 = '-o' ]; then
                  echo 'ASSIGNED P U HOTID SENDER   SENT     TIME  KEYWORD    SHORT DESCRIPTION'
                  STAT='[stat open]'
                  LAYOUT=""
               else
                  echo 'ASSIGNED P U HOTID STAT SENDER   SENT     TIME  KEYWORD    SHORT DESCRIPTION'
                  STAT='![stat closed]&&![stat cancel]'
                  LAYOUT="stat,"
               fi
               $OTPATH/ot_bugs -photline -l assigned,priority,urgency,num,${LAYOUT}sender,sdate,stime,keyword,desc\
                               -c -x "$STAT" | sort ;;
        '-'[aA])
               if [ $1 = '-a' ]; then
                  STAT='[stat open]'
                  LAYOUT=""
               else
                  STAT='![stat closed]&&![stat cancel]'
                  LAYOUT="stat,"
               fi
               echo 'yours:'
               $OTPATH/ot_bugs -photline -l num,${LAYOUT}priority,urgency,sender,sdate,stime,keyword,desc\
                               -x "[assigned `whoami`]&&$STAT"
               echo
               echo 'unassigned:'
               $OTPATH/ot_bugs -photline -l num,${LAYOUT}priority,urgency,sender,sdate,stime,keyword,desc\
                               -x '[assigned ""]&&'"$STAT"
               echo
               echo 'interested cc:'
               $OTPATH/ot_bugs -photline -l num,${LAYOUT}priority,urgency,assigned,sender,sdate,stime,keyword,desc\
                               -x "[cc `whoami`]&&$STAT" ;;
        '-s')  $OTPATH/ot_bugs -photline -l num,stat,assigned,priority,urgency,sdate,stime,keyword,desc\
                               -x "[sender `whoami`]&&([stat open]||[stat pending]||[stat defer])" ;;
        '-r')  $OTPATH/ot_bugs -photline -l num,stat,assigned,priority,urgency,sdate,stime,keyword,desc\
                               -x "[sender `whoami`]" ;;
        '-d')  $OTPATH/ot_bugs -photline -d ;;
        '-h'|'-help') more <<END
              ----------$PROGRAM usage----------
$PROGRAM              Create a new hotline to submit
$PROGRAM [-S] <hotid> Update a given hotline (silently if given -S)
$PROGRAM -v <hotid>   Output a given hotline on stdout for viewing
$PROGRAM -s [user]   
        List of open, defer, and pending hotlines submitted by you (or user)
$PROGRAM -o|-O [minutes] 
        List of open hotlines (open, defer, and pending hotlines if -O)
        Cycles if given <minutes>
$PROGRAM -r [user]    Record of all hotlines submitted by you (or user)
$PROGRAM -e           List every hotline in the database
$PROGRAM -x <code>    List using the tcl expression <code> as a search term
$PROGRAM -d           List of field names and the values they can have
$PROGRAM -help        Display this list
              ----------The Following are for CF only----------
$PROGRAM -a|-A [minutes]
        List of open hotlines (open, defer, and pending hotlines if -A) 
        assigned to you, un-assigned hotlines, and finally hotlines where
        you are on the interested CC list.  Cycles if given <minutes>
$PROGRAM -unlock <hotid>
        Unlock a locked hotline
$PROGRAM -phone <login>
        Use this to create a phone hotline where <login> is the login or
        mail address of the person leaving the message
$PROGRAM -top [count] [<mm/dd/yy>[-<mm/dd/yy>]]
        Top <count> (defaults to 10) hotline submitters for the given day(s)
        (default is for this calendar month)
$PROGRAM -summary [<mm/dd/yy>[-<mm/dd/yy>]]
        Summary of hotlines submitted for the given day(s)
        (default is for this calendar month)
$PROGRAM -escalation
        Generate an escalation report on open hotlines
END
               ;;
	'-top')            # Top report needs TOPCOUNT and INTERVAL
               REPORT=top
               TOPCOUNT=10
               MONTH=`date +%m`
               YEAR=`date +%y`
               INTERVAL="$MONTH/1/$YEAR-$MONTH/31/$YEAR" ;;
        '-summary')        # Summary needs INTERVAL
               REPORT=summary
               MONTH=`date +%m`
               YEAR=`date +%y`
               INTERVAL="$MONTH/1/$YEAR-$MONTH/31/$YEAR" ;;
        '-escalation')
               REPORT=escalation ;;
        *)     echo "Syntax error.  Run '$PROGRAM -help' for help."
               exit 1 ;;
      esac ;;

   ### Two Arguments to Hotline ###
   '2') case $1 in
        '-'[aA])
               if [ $1 = '-a' ]; then
                  STAT='[stat open]'
                  LAYOUT=""
               else
                  STAT='![stat closed]&&![stat cancel]'
                  LAYOUT="stat,"
               fi
               SECS=`expr "$2" \* 60`
               if [ $? -ne 0 ]||[ $SECS -lt 0 ]; then
                  echo "Syntax error.  Run '$PROGRAM -help' for help."
                  exit 1
               fi
               USER=`whoami`
               while true; do
                  cat <<END           # Cat buffers the output for us
`clear`                                                    `date`
yours:
`$OTPATH/ot_bugs -photline -l num,${LAYOUT}priority,urgency,sender,sdate,stime,keyword,desc -x "[assigned $USER]&&$STAT"`

unassigned:
`$OTPATH/ot_bugs -photline -l num,${LAYOUT}priority,urgency,sender,sdate,stime,keyword,desc -x '[assigned ""]&&'"$STAT`

interested cc:
`$OTPATH/ot_bugs -photline -l num,${LAYOUT}priority,urgency,assigned,sender,sdate,stime,keyword,desc -x "[cc $USER]&&$STAT"`
END
                  sleep $SECS
               done ;;
        '-'[oO])
               if [ $1 = '-o' ]; then
                  HEADER='ASSIGNED P U HOTID SENDER   SENT     TIME  KEYWORD    SHORT DESCRIPTION'
                  STAT='[stat open]'
                  LAYOUT=""
               else
                  HEADER='ASSIGNED P U HOTID STAT SENDER   SENT     TIME  KEYWORD    SHORT DESCRIPTION'
                  STAT='![stat closed]&&![stat cancel]'
                  LAYOUT="stat,"
               fi
              
               SECS=`expr "$2" \* 60`
               if [ $? -ne 0 ]||[ $SECS -lt 0 ]; then
                  echo "Syntax error.  Run '$PROGRAM -help' for help."
                  exit 1
               fi
               while true; do
                  cat <<END          # Cat buffers the output for us
`clear``date`

"$HEADER"
`$OTPATH/ot_bugs -photline -l assigned,priority,urgency,num,${LAYOUT}sender,sdate,stime,keyword,desc -c -x "$STAT" | sort`
END
                  sleep $SECS
               done ;;
        '-x')  $OTPATH/ot_bugs -photline -x "$2";;
        '-s')  $OTPATH/ot_bugs -photline -l num,stat,assigned,priority,urgency,sdate,stime,keyword,desc\
                               -x "[sender $2]&&([stat open]||[stat pending]||[stat defer])" ;;
        '-r')  $OTPATH/ot_bugs -photline -l num,stat,assigned,priority,urgency,sdate,stime,keyword,desc\
                               -x "[sender $2]" ;;
        '-v')  $OTPATH/ot_bugs -photline -fr -n $2 ;;
        '-S')  $OTPATH/ot -photline -s -u -n$2 ;;
        '-unlock')
               $OTPATH/otadmin -p hotline -u "$2" ;;
        '-phone')
               export OT_EDITOR
               export HOT_EDITOR                            # Save the editor for OT to use
               export HOT_SENDER                            # Save value for sender field
               if [ d$OT_EDITOR != d ]; then
                  HOT_EDITOR=$OT_EDITOR
               else
                  HOT_EDITOR=$EDITOR
               fi
               OT_EDITOR=$0                                 # Sets up hotline as editor for OT
               HOT_SENDER=$2                                # Save argument away in environment
               $OTPATH/ot -photline -e ;;                   # Causes 'hotline /tmp/file' to happen (see above)
        '-top')                                             # top needs INTERVAL and TOPCOUNT
               REPORT=top
               if expr $2 : '^[0-9]*$' >/dev/null; then     # if simple number, argument is TOPCOUNT
                   TOPCOUNT=$2
                   MONTH=`date +%m`                         # calculate INTERVAL
                   YEAR=`date +%y`
                   INTERVAL="$MONTH/1/$YEAR-$MONTH/31/$YEAR"
               else                                         # else argument is INTERVAL
                   TOPCOUNT=10
                   INTERVAL=$2                              # calculate TOPCOUNT
               fi ;;
        '-summary')                                         # summary needs INTERVAL (from argument)
               REPORT=summary
               INTERVAL=$2 ;;
        *)     echo "Syntax error.  Run '$PROGRAM -help' for help."
               exit 1 ;;
      esac ;;

   ### Three Arguments to Hotline ###
   '3') case $1 in
        '-top')                         # Top needs INTERVAL and TOPCOUNT (both from arguments)
               REPORT=top
               TOPCOUNT=$2
               INTERVAL=$3 ;;
        *)     echo "Syntax error.  Run '$PROGRAM -help' for help."
               exit 1 ;;
      esac ;;

   ### Four or more Arguments to Hotline ###
   *) echo "Syntax error.  Run '$PROGRAM -help' for help."
      exit 1 ;;
esac

##################################################
#  Complex Reports generated from this point on  #
##################################################
if [ d$REPORT = d ]; then
   exit                                         # No reports to generate so exit

####################
#  Summary Report  #
####################
elif [ d$REPORT = dsummary ]; then
   cat <<END

                               HOTLINE SUMMARY


Report Generated: `date +'%D %T'`       Report Covers: $INTERVAL
END
   echo "Hotlines in interval:"\
                         `$OTPATH/ot_bugs -photline -c -lstat -x "[sdate $INTERVAL]" | wc -l`    # wc produces extra spaces
   echo "Total hotlines open:" `$OTPATH/ot_bugs -photline -c -lstat -x '[stat open]' | wc -l`    # wc produces extra spaces
   echo                                                                                          # so use echo to rid them
   for FIELD in stat keyword priority urgency site method assigned; do                           # For each field
      echo $FIELD | sed -e 'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/'            # ToUpper field name
      $OTPATH/ot_bugs -photline -c -l$FIELD:11 -o$FIELD -x "[sdate $INTERVAL]" | uniq -c | awk ' # Count up values
BEGIN   { i=0 }
        { if( i==0 ) printf "\n";               # Nice column output
          if( $2=="" ) s="(blank)"; else s=$2   # with viewable blanks
          printf "%11.11s:%3.3s",s,$1;
          i=(i+1)%5
        }
END     { printf "\n\n" }'
   done
   echo CLOSED                                  # Special case for closed, check both fdate and sdate
   $OTPATH/ot_bugs -photline -c -lassigned -oassigned\
        -x "[fdate $INTERVAL]&&[sdate $INTERVAL]" | uniq -c | awk '
BEGIN   { i=0 }
        { if( i==0 ) printf "\n";               # Nice column output
          if( $2=="" ) s="(blank)"; else s=$2   # with viewable blanks
          printf "%11.11s:%3.3s",s,$1;
          i=(i+1)%5
        }
END     { printf "\n\n" }'

################
#  Top Report  #
################
elif [ d$REPORT = dtop ]; then
   cat <<END

                           TOP $TOPCOUNT HOTLINE SUBMITTERS


Report Generated: `date +'%D %T'`       Report Covers: $INTERVAL

END
   $OTPATH/ot_bugs -photline -c -lsender -osender -x "[sdate $INTERVAL]" | uniq -c |\
           sort -r | head -$TOPCOUNT | while read COUNT SENDER; do   # Foreach top user and there count
      echo "$SENDER: $COUNT"
      $OTPATH/ot_bugs -photline -c -lkeyword -okeyword\
              -x "[sdate $INTERVAL]&&[sender $SENDER]" | uniq -c | sort -r | awk '
BEGIN   { i=0 }                                                      # Generate a keyword report
        { if( i==0 ) printf "\n";               # Nice column output
          if( $2=="" ) s="(blank)"; else s=$2   # with viewable blanks
          printf "%11.11s:%3.3s",s,$1;
          i=(i+1)%5
        }
END     { printf "\n\n" }'
   done
#######################
#  Escalation Report  #
#######################
elif [ d$REPORT = descalation ]; then
   echo "Report Generated on: "`date`
   echo
   echo "                           Unassigned Hotlines"
   echo "                           ==================="
   echo
   $OTPATH/ot_bugs -photline -lnum,priority,urgency,sender,sdate,stime,keyword,desc \
                   -x '![stat closed]&&![stat cancel]&&[assigned ""]'
   echo
   /usr/local/bin/perl <<END

# The following time code is lifted, with minor syntactical changes,
# from the OSF/1 ctime code.  Thanks to OSF/1 for saving me the effort of
# trying to figure out how to do this - which I wouldn't be able to do -
# and thanks to Larry Wall for perl.  Yowza!

@mdays = (0,31,59,90,120,151,181,212,243,273,304,334,-1,-1);

sub YR {
  local(\$A) = @_;
  return int ((1900+\$A)*365 +(1900+\$A)/4 - (1900+\$A)/100 + ((1900+\$A) - 1600)/400);
}

sub dysize {
  local(\$A) = @_;
  return (((1900+(\$A)) % 4 == 0 && (1900+(\$A)) % 100 != 0 || (1900+(\$A)) % 400 == 0) ? 366:365);
}

sub mktime {
  local(\$tm_sec, \$tm_min, \$tm_hour, \$tm_mday, \$tm_mon, \$tm_year) = @_;
  local(\$days, \$secs);

  if (\$tm_mon < 0) {
lt_repeat:
    \$tm_year--;
    \$tm_mon += 12;
    if (\$tm_mon < 0) { goto lt_repeat; }
      \$days = \$mdays[\$tm_mon];
    }
    elsif (\$tm_mon > 11) {
gt_repeat:
      \$tm_year++;
      \$tm_mon -= 12;
      if (\$tm_mon > 11) { goto gt_repeat; }
        \$days = \$mdays[\$tm_mon];
      } else { \$days = \$mdays[\$tm_mon]; }

  \$days += (\$tm_mday - 1);

  \$days += (&YR(\$tm_year)) - (&YR(70));
  if (&dysize(\$tm_year) == 366) { \$days--; }
  if ((&dysize(\$tm_year) == 366) && (\$tm_mon > 1)) { \$days++; }

  \$secs = \$days * 86400;
  \$secs += (\$tm_hour*60 + \$tm_min)*60 + \$tm_sec;
      
  return \$secs;
}

# End lifted time code.

# Begin constants.
#
# The amount of time in seconds at which each priority level should be
# escalated.  e.g. priority 0 gets escalated every 3600 seconds (1 hr),
# and priority 3 gets escalated every 259200 seconds (48 hrs).
@priorities = (3600, 7200, 86400, 259200);

# Location of date command.
\$date_command = '/bin/date';
# End constants.

# Find out the time now in seconds since Jan. 1, 1970.
\$time_now = &date_to_seconds(\`\$date_command +%T\`, \`\$date_command +%D\`);

# Read the result of the 'ot_bugs' command from STDIN.
open( INPUT, "$OTPATH/ot_bugs -c -photline -x '[stat open] && [stime] != \"\"' -l priority,sdate,stime:8,num,sender,assigned,desc | sort |" );
while(<INPUT>) {
  (\$priority, \$date, \$time, \$the_rest) = unpack("A2A9A9A*", \$_);
  \$time_then = &date_to_seconds(\$time, \$date);
  if (\$priority ne '') {
    \$stars = &mkstars(\$time_then, \$priority);  
    if (\$stars ne '') {
      write;
    }
  }
}

# Begin procedures
sub date_to_seconds {
  local(\$time, \$date) = @_;
  local(\$hour, \$mins, \$secs);
  local(\$mon, \$mday, \$year);

  (\$hour, \$mins, \$secs) = split(':', \$time);
  (\$mon, \$mday, \$year) = split('/', \$date);

  return &mktime(\$secs, \$mins, \$hour, \$mday, \$mon, \$year);
} 

sub mkstars {
  local(\$time_then, \$priority) = @_;
  local(\$time_diff, \$period, \$number);
  local(\$star) = '*';
  local(\$stars) = '';
  local(\$index) = 0;

  \$time_diff = \$time_now - \$time_then;
  if (\$time_diff >= 2678400) {
    \$stars = '???';
    return \$stars;
  }
  \$period = \$priorities[\$priority];
  \$number = int(\$time_diff / \$period);

  \$index = 0;
  if (\$number > 5) { return ":-("; }
  else {
    while (\$index < \$number) {
      \$stars = \$stars . \$star;
      \$index++;
    }
  }
  return \$stars;
}

format top =
                        Hotline Escalation Report
                        =========================

      P SENT     TIME     HOTID SENDER   ASSIGNED SHORT DESCRIPTION
--------------------------------------------------------------------------------
.

format STDOUT =
@>>>> @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
\$stars, \$_
.
END
fi
