#!/bin/bash
#
# $Id: calltrace_generate,v 1.2 2002/05/15 07:33:55 icahoon Exp $
#
# ====================================================================
# The Vovida Software License, Version 1.0 
# 
# Copyright (c) 2000 Vovida Networks, Inc.  All rights reserved.
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in
#    the documentation and/or other materials provided with the
#    distribution.
# 
# 3. The names "VOCAL", "Vovida Open Communication Application Library",
#    and "Vovida Open Communication Application Library (VOCAL)" must
#    not be used to endorse or promote products derived from this
#    software without prior written permission. For written
#    permission, please contact vocal\@vovida.org.
# 
# 4. Products derived from this software may not be called "VOCAL", nor
#    may "VOCAL" appear in their name, without prior written
#    permission of Vovida Networks, Inc.
# 
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
# NON-INFRINGEMENT ARE DISCLAIMED.  IN NO EVENT SHALL VOVIDA
# NETWORKS, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT DAMAGES
# IN EXCESS OF $1,000, NOR FOR ANY INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES LOSS OF USE, DATA, OR
# PROFITS OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
# DAMAGE.
# 
# ====================================================================
# 
# This software consists of voluntary contributions made by Vovida
# Networks, Inc. and many individuals on behalf of Vovida Networks,
# Inc.  For more information on Vovida Networks, Inc., please see
# <http://www.vovida.org/>.
#

version="\$Id: calltrace_generate,v 1.2 2002/05/15 07:33:55 icahoon Exp $"

######################################################################
#
#   Load libraries
#
######################################################################

lib_path="${0%/$(basename $0)}"

. $lib_path/vocal_html_lib

log_level=$log_warning

exec_path=$($cd $lib_path && echo $PWD)

######################################################################
#
#   Local functions
#
######################################################################

function    get_date_and_time()
{
    log $log_verbose "get_date_and_time: $*"

    local date=$($head -1 "$*")
    date="${date%% *}"

    log $log_verbose "$date"

    $print "$date"
}

function   get_gkid()
{
    log $log_verbose "get_gkid: $*"
    
    local   gkid=$($head -30 "$1" | $egrep "gatekeeperIdentifier:")
    gkid=${gkid#*: }
    
    $print $gkid
}

function    get_eptid()
{
    log $log_verbose "get_eptid: $*"
    
    local   eptid=$($head -30 "$1" | $egrep "endpointIdentifier:")
    eptid=${eptid#*: }
    
    $print $eptid
}


######################################################################
#
#   Command line parsing / Usage 
#
######################################################################

usage="usage:   $($basename $0) [options] in_file output_directory images_directory
   or    $($basename $0) [-v|--version]
options:
         -C | --cisco  	    	    Use Cisco branding
         -l | --log_level level     warning (default), info, debug, verbose
	 -o | --output file         defaults to index.html"


#
#   Version option
#   

if [ $# -eq 1 ]; then
    if [  "$1" = "-v" -o "$1" = "--version" ]; then
    	$print $version
    	exit 0
    fi
fi


#
#   Parse options
#
#

assert [ $# -ge 3 ]

cmd_line="$*"

branding=""

output_file="index.html"

options_done=0

while [ ! $options_done -eq 1 ]
do
    case $1 in

    	-C | --cisco )
	    background_image="$image_dir/crumpled.jpg"
	    brand_image="$image_dir/cisco.gif"
	    brand_name="Cisco"
	    brand_link="http://www.cisco.com"
	    branding="$1"
	    shift
    	;;
	
	-l | --log_level )

    	    shift    	    
	    case $1 in
		info )
		    log_level=$log_info
		    shift
		;;
		debug )
		    log_level=$log_debug
		    shift
		;;
		verbose )
		    log_level=$log_verbose
		    shift
		;;
	    esac
	;;
	
	-o | --output )
	    
	    shift
	    if [ -n "$1" ]; then
	    	output_file="$1"
		shift
	    fi
    	;;	    

    	* )
	    options_done=1
	;;

    esac
done

log $log_info "\nVersion: $version\nCommand: $0 $cmd_line"
log $log_info "branding:              $branding"
log $log_info "log level:             $log_level"
log $log_info "output file:           $output_file"


# 
#   Parse parameters
#

assert [ $# -ge 3 ]

assert [ -r "$1" ]

in_file="$1"

log $log_info "in_file:               $in_file"


#
#   output_directory parameter
#

output_directory="$2"

make_dir "$output_directory"

output_directory=$($cd $output_directory && echo $PWD)



#
#   images_directory
#

assert [ -d "$3" ]

images_directory="$($cd $3 && echo $PWD)"

log $log_info "images_directory:      $images_directory"


######################################################################
#
#   Application
#
######################################################################

#
#   Create the new subdirectory
#

start_time=$(get_date_and_time $in_file)
log $log_info "start_time:            $start_time"

gatekeeper_identifier=$(get_gkid $in_file)
gatekeeper_instance=$gatekeeper_identifier.$start_time
log $log_info "gatekeeper_instance:   $gatekeeper_instance"

endpoint_identifier=$(get_eptid $in_file)
log $log_info "endpoint_identifier:   $endpoint_identifier"

output_directory="$output_directory/$gatekeeper_instance"
make_dir "$output_directory"

log $log_info "output_directory:      $output_directory"

make_sym_link $images_directory $output_directory/images
images_directory="$output_directory/images"


#
#   Copy the log file
#

$cp $in_file "$output_directory/log.txt"
assert [ $? -eq 0 ]

in_file="$output_directory/log.txt"

#
#   Parse the endpoints
#

log $log_info "Parsing endpoints:     $(date)"
$exec_path/parseEndpoints $in_file $output_directory
assert [ $? -eq 0 ]

#
#   Parse the calls
#

log $log_info "Parsing calls:         $(date)"
$exec_path/parseCalls $in_file $output_directory
assert [ $? -eq 0 ]


#
#   Create for html individual call and registration directories
#

unknown_endpoint="unknownEndpoint"
unknown_ept_dir="$output_directory/$unknown_endpoint"
calltrace2html="$exec_path/calltrace2html"

for ept in $output_directory/${endpoint_identifier}* $unknown_ept_dir
do
    log $log_info "Creating html for endpoint: $ept"

    unknown_ept=0
    
    if [ "$ept" = "$unknown_ept_dir" ]; then
    	unknown_ept=1
    fi
    
    old_pwd="$PWD"

    if [ -d $ept/registrations ]; then
    	$cd $ept/registrations
    	log $log_info "  ... $ept/registrations/index.html"
    	$calltrace2html $images_directory $branding > index.html
        $cd $old_pwd
    fi

    if [ -d $ept/calls ]; then

    	for call in $ept/calls/*
	do
	    if [ ! -d $call ]; then
	    	continue
	    fi
    	    $cd $call
    	    log $log_info "  ... $call/index.html"
	    if [ $unknown_ept -eq 1 ]; then
	    	$calltrace2html $images_directory $branding -c -u > index.html
	    else
	    	$calltrace2html $images_directory $branding -c > index.html
	    fi
	    $cd $old_pwd
	done

    else
    	log $log_debug "$ept/calls does not exist."
    fi
done


#
#   Accumulate the aliases in the unknownEndpoints
#

sorted_by_alias="sorted_by_alias"
calls="calls"
phone_number="phone_number"

if [ -d $unknown_ept_dir -a \( -d $unknown_ept_dir/$calls \) ]; then

    log $log_info "Creating alias index for: $unknown_endpoint"

    old_pwd="$PWD"

    $cd $unknown_ept_dir
    
    $find calls -name "$phone_number" | while read phone_number_file
    do
	make_dir $sorted_by_alias
	$cd $sorted_by_alias

	phone_number_dir=$($cat ../$phone_number_file)

	make_dir $phone_number_dir
	$cd $phone_number_dir

	make_dir $calls
	$cd $calls

	call_target="../../../${phone_number_file%%/$phone_number}"

	make_sym_link $call_target

	$cd $unknown_ept_dir

    done

    $cd $old_pwd

fi


#
#   Accumulate the aliases of known endpoints
#

old_pwd="$PWD"

$cd $output_directory

for ept in ${endpoint_identifier}*
do

    log $log_info "Creating alias index for: $ept"

    $find $ept -name "$phone_number" | while read phone_number_file
    do
    	make_dir $sorted_by_alias
	$cd $sorted_by_alias

	phone_number_dir=$($cat ../$phone_number_file)

	make_dir $phone_number_dir
	$cd $phone_number_dir

    	make_sym_link ../../$ept

    	log $log_info "  ... $ept"	

	$cd $output_directory

    done
    
done

$cd $old_pwd

#
#   Link unknown aliases to known aliases, if possible.
#

if [ -d $unknown_ept_dir -a \( -d $unknown_ept_dir/$sorted_by_alias \) ]; then

    log $log_info "Mapping unknown aliases to known aliases."

    $cd $output_directory/$sorted_by_alias
    
    for path_to_alias in $unknown_ept_dir/$sorted_by_alias/*
    do
    	alias=${path_to_alias##*/}

	make_dir $alias
	$cd $alias
	
    	make_sym_link $path_to_alias $unknown_endpoint
	
	$cd $output_directory/$sorted_by_alias
    done
    	
    $cd $old_pwd        
fi

#
#   Sort calls by time and by callid
#

sorted_by_callid="sorted_by_callid"
sorted_by_time="sorted_by_time"

if [ -d $output_directory/$sorted_by_alias ]; then

    log $log_info "Sorting calls by time and callid."

    $cd $output_directory/$sorted_by_alias

    for i in *
    do
    	cd $i

	$find . -name "start_time" -follow | $egrep "calls" | while read call
	do
	    make_dir $sorted_by_time
	    time_dir=${call%*/start_time}
	    time_dir=../${time_dir#./*}
	    cd $sorted_by_time
	    make_sym_link $time_dir $($cat ../${call#./*})
	    cd ..
	done

	$find . -name "calls" -follow | while read call
	do
    	    make_dir $sorted_by_callid
	    cd $sorted_by_callid
	    for i in ../${call#./*}/*
	    do
	    	if [ -d $i ]; then
	    	    make_sym_link $i
	    	fi
	    done
	    cd ..
	done

	cd ..
    done

    $cd $old_pwd
fi

#
#   Title variables
#
#   	Uses the gatekeeper_instance
#

title="Sip to H.323 Call Signaling Gateway: $gatekeeper_instance"

log $log_info "title:                 $title"

title_html="
${content_indent}<h2>
${content_indent_2}Sip to H.323 Call Signaling Gateway: $gatekeeper_instance
${content_indent}</h2>"

#
#   Number of total rows in the call trace table
#

num_aliases=$($ls -1 $output_directory/$sorted_by_alias 2>/dev/null | $wc -l)
num_reg=$($ls -1d $output_directory/$sorted_by_alias/*/*/registrations 2>/dev/null | $wc -l)
num_calls=$($ls -1d $output_directory/$sorted_by_alias/*/*/calls/* 2>/dev/null | $wc -l)

num_rows=0

#
# White cap (1) + top outline (1) + gatekeeper (1) 
#   + rows per alias (5 * num_aliases) + number of registrations
#   + row per call (2 * num_calls) + bottom outline (1)
#

let "num_rows = 1 + 1 + 1 + (5 * $num_aliases) + $num_reg + (2 * $num_calls) + 1"

log $log_info "number of aliases:       $num_aliases"
log $log_info "number of registrations: $num_reg"
log $log_info "number of calls:         $num_calls"
log $log_info "number of rows:          $num_rows"

#
#   clear image
#

clear_image="<img width=\"1\" border=\"0\" src=\"images/clear.gif\">"

#
#   gatekeeper background color
#   even background color / odd background color
#

gatekeeper_bg_color="#CCCCCC"
even_bg_color="#EEEEEE"
odd_bg_color="#DDDDDD"

bg_color=""

function get_next_bg_color()
{
    if [ "$bg_color" = "$even_bg_color" ]; then
    	$print "$odd_bg_color"
    else
    	$print "$even_bg_color"
    fi
}

function    blank_alias_row()
{
    $print "
$row_begin
$(cell_begin 0 0 0 center center \#000000 5)${clear_image}$cell_end
$(cell_begin 0 8 0 center center $bg_color) &nbsp; $cell_end
$(cell_begin 0 0 0 center center \#000000 5)${clear_image}$cell_end
$row_end
"
}


#
#   Table outline
#

table_outline="
$row_begin
$(cell_begin 0 10 0 center center \#000000 5)${clear_image}$cell_end
$row_end
"

#
#   Gatekeeper header
#

gatekeeper_header="
$row_begin
$(cell_begin 0 0 0 center center \#000000)${clear_image}$cell_end
$(cell_begin 0 2 0 left center $gatekeeper_bg_color)
${content_indent}<br>&nbsp;
${content_indent}$(strong "H.323 Translator:") $gatekeeper_identifier
${content_indent}<br><br>
${cell_indent}$cell_end
$(cell_begin 0 3 0 left center $gatekeeper_bg_color)
${content_indent}&nbsp;
${content_indent}$(strong "Start Time:") ${start_time}<br>
${cell_indent}$cell_end
$(cell_begin 0 3 0 left center $gatekeeper_bg_color)
${content_indent}&nbsp;
${content_indent}<a href=\"./log.txt\">Log File</a>
${cell_indent}$cell_end
$(cell_begin 0 0 0 center center \#000000)${clear_image}$cell_end
$row_end"

#
#   Call trace table cap
#

call_trace_table_cap="
$row_begin
$(cell_begin 10 0 $num_rows) &nbsp; $cell_end
$(cell_begin)${clear_image}$cell_end
$(cell_begin 10) &nbsp; $cell_end
$(cell_begin 10) &nbsp; $cell_end
$(cell_begin 10) &nbsp; $cell_end
$(cell_begin 10) &nbsp; $cell_end
$(cell_begin 10) &nbsp; $cell_end
$(cell_begin 10) &nbsp; $cell_end
$(cell_begin 10) &nbsp; $cell_end
$(cell_begin 10) &nbsp; $cell_end
$(cell_begin)${clear_image}$cell_end
$(cell_begin 9 0 $num_rows) &nbsp; $cell_end
$row_end
$table_outline $gatekeeper_header"


#
#   alias markup
#
#   	$1: phone number directory
#


function    alias_markup()
{
    local   alias_dir="$*"
    local   phone_number=$($basename $alias_dir)
    local   count=0
    
    $print "
$table_outline    
$row_begin
$(cell_begin 0 0 0 center center \#000000 5)${clear_image}$cell_end
$(cell_begin 0 2 0 left center $bg_color)
${content_indent}<br>&nbsp; 
${content_indent}$(strong "Phone Number:") $phone_number
${cell_indent}$cell_end
$(cell_begin 0 3 0 left center $bg_color)
${content_indent}<br>&nbsp;$(strong "Registration by EndpointId:")
${cell_indent}$cell_end
$(cell_begin 0 3 0 left center $bg_color)
${content_indent}<br>&nbsp;$(strong "Time:")
${cell_indent}$cell_end
$(cell_begin 0 0 0 center center \#000000 5)${clear_image}$cell_end
$row_end"

    $find $alias_dir -name "registrations" -follow | while read reg_file
    do
    	local endpoint_id=$($basename ${reg_file%*/registrations})
	
    	$print "
$row_begin
$(cell_begin 0 0 0 center center \#000000 5)${clear_image}$cell_end
$(cell_begin 0 2 0 left center $bg_color)
${content_indent}&nbsp; 
${cell_indent}$cell_end
$(cell_begin 0 3 0 left center $bg_color)
${content_indent}&nbsp;
${content_indent}<a href=\"$reg_file\">
${content_indent_2}${endpoint_id}</a>
${cell_indent}$cell_end
$(cell_begin 0 3 0 left center $bg_color)
${content_indent}&nbsp; $($cat $reg_file/start_time)
${cell_indent}$cell_end
$(cell_begin 0 0 0 center center \#000000 5)${clear_image}$cell_end
$row_end"

    done

    $print "
$row_begin
$(cell_begin 0 0 0 center center \#000000 5)${clear_image}$cell_end
$(cell_begin 0 2 0 left center $bg_color)
${content_indent}<br>&nbsp;$(strong "Calls By Time:") 
${cell_indent}$cell_end
$(cell_begin 0 2 0 left center $bg_color)
${content_indent}<br>&nbsp;$(strong "Direction:") 
${cell_indent}$cell_end
$(cell_begin 0 2 0 left center $bg_color)
${content_indent}<br>&nbsp;$(strong "Calling:")
${cell_indent}$cell_end
$(cell_begin 0 2 0 left center $bg_color)
${content_indent}<br>&nbsp;$(strong "Called:") 
${cell_indent}$cell_end
$(cell_begin 0 0 0 center center \#000000 5)${clear_image}$cell_end
$row_end"

    if [ -e $alias_dir/$sorted_by_time ]; then
    	count=0
    	for i in $alias_dir/$sorted_by_time/*
	do
	    if [ -L $i ]; then
	    	let "count = count + 1"
    	    	$print "
$row_begin
$(cell_begin 0 0 0 center center \#000000 5)${clear_image}$cell_end
$(cell_begin 0 2 0 left center $bg_color)
${content_indent}${count})&nbsp; 
${content_indent}<a href=\"$i\">
${content_indent_2}$($basename $i)</a>
${cell_indent}$cell_end
$(cell_begin 0 2 0 left center $bg_color)
${content_indent}&nbsp; $($cat $i/direction)
${cell_indent}$cell_end
$(cell_begin 0 2 0 left center $bg_color)
${content_indent}&nbsp; $($cat $i/calling)
${cell_indent}$cell_end
$(cell_begin 0 2 0 left center $bg_color)
${content_indent}&nbsp; $(cat $i/called)
${cell_indent}$cell_end
$(cell_begin 0 0 0 center center \#000000 5)${clear_image}$cell_end
$row_end"
    	    fi
	done
    fi

    $print "
$row_begin
$(cell_begin 0 0 0 center center \#000000 5)${clear_image}$cell_end
$(cell_begin 0 2 0 left center $bg_color)
${content_indent}<br>&nbsp;$(strong "Calls By CallId:") 
${cell_indent}$cell_end
$(cell_begin 0 2 0 left center $bg_color)
${content_indent}<br>&nbsp;$(strong "Direction:") 
${cell_indent}$cell_end
$(cell_begin 0 2 0 left center $bg_color)
${content_indent}<br>&nbsp;$(strong "Calling:") 
${cell_indent}$cell_end
$(cell_begin 0 2 0 left center $bg_color)
${content_indent}<br>&nbsp;$(strong "Called:") 
${cell_indent}$cell_end
$(cell_begin 0 0 0 center center \#000000 5)${clear_image}$cell_end
$row_end"

    if [ -e "$alias_dir/$sorted_by_callid" ]; then
    	count=0
    	for i in $alias_dir/$sorted_by_callid/*
	do
	    if [ -L $i ]; then
	    	let "count = count + 1"
    	    	$print "
$row_begin
$(cell_begin 0 0 0 center center \#000000 5)${clear_image}$cell_end
$(cell_begin 0 2 0 left center $bg_color)
${content_indent}${count})&nbsp; 
${content_indent}<a href=\"$i\">
${content_indent_2}$($basename $i)</a>
${cell_indent}$cell_end
$(cell_begin 0 2 0 left center $bg_color)
${content_indent}&nbsp; $($cat $i/direction)
${cell_indent}$cell_end
$(cell_begin 0 2 0 left center $bg_color)
${content_indent}&nbsp; $($cat $i/calling)
${cell_indent}$cell_end
$(cell_begin 0 2 0 left center $bg_color)
${content_indent}&nbsp; $(cat $i/called)
${cell_indent}$cell_end
$(cell_begin 0 0 0 center center \#000000 5)${clear_image}$cell_end
$row_end"
    	    fi
    	done
    fi

$print "$(blank_alias_row)"

}

#
#   Generate the html
#

cd $output_directory

if [ ! -e $sorted_by_alias ]; then
    log $info "No aliases. Exiting early."
    exit 0
fi

log $log_info "Generating html: ./$output_file"

$print "$(html_start) $(brand_information)" > ./$output_file

$print "
$table_begin
$call_trace_table_cap" >> ./$output_file

for i in ./$sorted_by_alias/*
do
    bg_color=$(get_next_bg_color)
    $print "$(alias_markup $i)" >> ./$output_file
done

$print "
$table_outline
$(blank_row 12 \#FFFFFF "&nbsp;<br><br><br>")\n
$table_end
$html_end
" >> ./$output_file
