#!/usr/bin/perl

use strict;
use warnings;

sub cannot_show() {
  print "Error: Unable to detect console logfile\n";
  print "(Note: This only works if arb was started via the script 'arb')\n";
  die "\n";
}

sub show_log_with_less($$) {
  my ($log,$lessopt) = @_;
  print "Showing $log using less..\n";
  my $cmd = "less $ {lessopt} \"$log\"";
  # system($cmd)==0 || die "error executing '$cmd' (result=$?)"; # always fails when less is interrupted
  system($cmd);
}

sub main() {
  if (scalar(@ARGV)!=1) {
    die "Usage: arb_show_log.pl logname\n ";
  }

  my $logname = $ARGV[0];
  my $server_log = $ENV{ARB_SERVER_LOG};
  if (not defined $server_log) {
    print "Environment variable ARB_SERVER_LOG is not defined\n";
    cannot_show();
  }

  if ($server_log =~ /\/([^\/]+)$/o) {
    my $logdir = $`;
    my $runlog = undef;
    my $lessopt = '+F';
    if ($logname eq 'sysinf') {
      $runlog = $logdir.'/sys.info';
      $lessopt = ''; # do not show tail
    }
    else {
      $runlog = $logdir.'/'.$logname.'.log';
    }
    if (-f $runlog) {
      show_log_with_less($runlog, $lessopt);
    }
    else {
      print "Expected logfile '$runlog' not found\n";
      cannot_show();
    }
  }
  else {
    print "Expected ARB_SERVER_LOG to contain a logfile name\n";
    print "(contains '$server_log')\n";
    cannot_show();
  }
}
main();
