#!/bin/bash

#this script is executed whenever you click on an entry from the logviewer script. This script handles opening a text editor to view your log file.

DIRECTORY="$(readlink -f "$(dirname "$(dirname "$0")")")"

file="$6"
if [ -z "$file" ];then
  file="$1"
fi
echo "$file" > "$DIRECTORY/data/current-viewed-logfile"

echo "viewlog: Viewing file: $file" 1>&2

if command -v mousepad ;then
  
  #Mousepad on Bullseye uses DBus and a tabbed interface to combine instances.
  #Use command-line flags to prevent this, but only if they are available. (Don't break Buster)
  if mousepad --help | grep -q '\--opening-mode' ;then
    mousepad "$file" -o window --disable-server &
  else
    mousepad "$file"
  fi
  pid=$!
elif command -v leafpad ;then
  leafpad "$file" &
  pid=$!
else
  #for text_editor function
  source "${DIRECTORY}/api"
  text_editor "$file" &
  pid=$!
fi

echo "PID is $pid" 1>&2

#while the user-selection stays the same, AND the text editor is still running, wait.
while [ "$(cat "$DIRECTORY/data/current-viewed-logfile")" == "$file" ] && [ -f /proc/$pid/status ];do
  sleep 1
done
kill $pid 2>/dev/null


