#!/usr/bin/env perl
#
# auto-record ARB-session
# (for debugging purposes; user could as well record ARB crashes)
#
# call via:
# arb_ntree --execute _dolog database.arb
#
# rerun via
# arb_ntree --execute _logged database.arb


use strict;
use warnings;

use lib "$ENV{'ARBHOME'}/lib/";
use ARB;

my $logged_amc = '_logged.amc';

my $gb_main = ARB::open(":","r");
if (not $gb_main) {
  my $error = ARB::await_error();
  die "$error";
}

my $macrodir = ARB::getenvARBMACROHOME();
if (defined $macrodir) {
  if (not -d $macrodir) { die "No such directory '$macrodir'"; }
  my $last_logged = $macrodir.'/'.$logged_amc;
  if (-f $last_logged) {
    my $backupDir = $macrodir.'/_backup';
    if (not -d $backupDir) {
      mkdir($backupDir) || die "Failed to create directory '$backupDir' (Reason: $!)";
    }
    my $modtime = (stat $last_logged)[9];
    my $backup = $backupDir.'/_logged_'.$modtime.'.amc';
    print "backup '$last_logged' -> '$backup'\n";
    my $cmd = "cp -p $last_logged $backup";
    system($cmd)==0 || die "Failed to execute '$cmd'";
  }

  BIO::remote_action($gb_main,"ARB_NT","macros");
  BIO::remote_awar($gb_main,"ARB_NT","tmp/macro/file_name",$logged_amc);
  BIO::remote_action($gb_main,"ARB_NT","MACROS/macro_record"); # hack :)
  BIO::remote_action($gb_main,"ARB_NT","MACROS/CLOSE");
}
ARB::close($gb_main);
