#!/bin/bash
#
# Copyright (c) 2010, 2011 CNRS
# Authors: Joseph Mirabel
#
#
# This file is part of hpp-tools
# hpp-tools is free software: you can redistribute it
# and/or modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation, either version
# 3 of the License, or (at your option) any later version.
#
# hpp-tools is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty
# of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Lesser Public License for more details.  You should have
# received a copy of the GNU Lesser General Public License along with
# hpp-tools  If not, see
# <http://www.gnu.org/licenses/>.

if [ $# -gt 0 ]; then
	pgname=$1
else
	pgname="hppcorbaserver"
fi

function ctrl_c () {
	killtail
	exit 1
}

function killtail() {
	if [ -n "$tail_pid" ]; then
		kill $tail_pid
		wait $tail_pid 2> /dev/null
		tail_pid=""
	fi
}

echo_() {
	echo "$@" >&2
}

install_dir="${INSTALL_HPP_DIR-"${DEVEL_HPP_DIR}/install"}"
LOG_DIR=$install_dir/var/log/hpp

pid=""
test -z "$LOGTAIL_TYPE" && LOGTAIL_TYPE="journal"
type=$LOGTAIL_TYPE
delay_short=5
delay_long=10
delay=$delay_long
trap ctrl_c INT
echo_ "=========================== Checking $pgname logs ============================"
while [ 0 -eq 0 ]; do
	new_pid=`pidof $pgname`
  if [ ! $(echo $new_pid | grep -o " " | wc -l ) -eq 0 ]; then
    echo_ "======================= Several session detected ======================="
  else
    if [ ! "$pid" == "$new_pid" ]; then
      pid=$new_pid
      if [ -n "$pid" ]; then
        if [ -e $LOG_DIR/$type.$pid.log ]; then
          delay=$delay_long
          echo_ "======================= New $pgname session - $pid ======================="
          tail --pid=$pid -f $LOG_DIR/$type.$pid.log | \
            sed --unbuffered -E "s/([A-Z]+):(\/[^\/]+)+\/([kh]pp[-/][a-z-]+)\/[^:]+:([0-9]+:)?/\1:\3:/" \
            | highlight --config-file="/tmp/cmeel-hxkroz0x/whl/cmeel.prefix/etc/hpp-tools/highlight/log.lang" --style=darkness --out-format=xterm256 --syntax=log &
          tail_pid=$!
        else
          delay=$delay_short
          pid=""
        fi
      else
        if [ -n "$tail_pid" ]; then
          echo_ "----------------------------- No $pgname session -----------------------------"
        fi
      fi
    fi
  fi
	sleep $delay
done
