#!/bin/bash

###########################################################
## Copyright (c) 2002-2024 Alexey Kuryakin daqgroup@mail.ru
###########################################################

###########################################################
## wintail - simulate Windows command (wintail) on Linux
## wintail uses to view LOG files
###########################################################

###########################################################
source $(crwkit which crwlib_base.sh); # Use base library #
source $(crwkit which crwlib_file.sh); # Use file library #
###########################################################

function execute(){
 if which $1 >/dev/null 2>&1; then
  exec "$@";
 else
  echo "$(basename ${BASH_SOURCE[0]}): could not find $1" 1>&2;
 fi;
};

function xterm_cat(){
 xterm -fa 'PT Mono' -fs 12 -fg white -bg black -sb -rightbar -hold -geometry 138x35+50+130 -title "cat $*" -e cat "$@";
};

function xterm_tail(){
 local opt="-n 1000 -F";
 xterm -fa 'PT Mono' -fs 12 -fg white -bg black -sb -rightbar -hold -geometry 138x35+50+130 -title "tail $opt $*" -e tail $opt "$@";
};

function xterm_mcview(){
 xterm -fa 'PT Mono' -fs 12 -fg white -bg black -sb -rightbar -hold -geometry 138x35+50+130 -title "mcview $*" -e mcview "$@";
};

function config_logger(){
 local loggers="klogg glogg";
 local cmd="$(basename $1)";
 if word_is_in_list $cmd $loggers; then
  for logger in $loggers; do
   if [ -e "$scriptHOME/$logger.conf" ] && [ ! -e "$HOME/.config/$logger/$logger.conf" ]; then
    if [ ! -d "$HOME/.config/$logger" ]; then mkdir $HOME/.config/$logger; fi;
    cp -fv $scriptHOME/$logger.conf $HOME/.config/$logger/$logger.conf;
   fi;
  done;
 fi;
};

function get_logger(){
 unix getapppath klogg glogg okular mcview -t text/plain -a .log firefox -t text/html tail cat;
};

function main(){
 local exe="$(get_logger "$1")";
 if [ -z "$exe" ]; then
  1>&2 echo "Error: could not find viewer.";
  exit 1;
 fi;
 config_logger $exe;
 case $(basename $exe) in
  cat)    xterm_cat    "$@"; ;;
  tail)   xterm_tail   "$@"; ;;
  mcview) xterm_mcview "$@"; ;;
  *)      execute $exe "$@"; ;;
 esac;
};

main "$@";

##############
## END OF FILE
##############
