#!/usr/bin/env perl
use strict;
use warnings;
use lib 'lib';
use TAEB;

if (grep { $_ eq '--help' } @ARGV) {
    print STDERR <<"USAGE";
TAEB $TAEB::VERSION - the Tactical Amulet Extraction Bot
Options:
    --rc         Print TAEB's required nethackrc to stdout
    --loop       Run TAEB repeatedly
    --help       Print this message
USAGE
    exit 0;
}
if (grep { $_ eq '--rc' } @ARGV) {
    print TAEB->config->nethackrc_contents;
    exit 0;
}
my $loop = grep { $_ eq '--loop' } @ARGV;

my $tstp = $SIG{TSTP} = sub {
    # if we don't invoke TSTP then we won't be suspended
    $SIG{TSTP} = 'DEFAULT';

    TAEB->display->deinitialize;

    kill TSTP => $$;
};

$SIG{CONT} = sub {
    $SIG{TSTP} = $tstp;

    TAEB->display->reinitialize;
};

$SIG{TERM} = sub {
    $SIG{TERM} = 'DEFAULT';

    TAEB->display->deinitialize;

    kill TERM => $$;
};

$| = 1;

while (1) {
    eval {
        local $SIG{INT} = sub { die "Interrupted.\n"; $loop = 0 };
        my $report = TAEB->play;
        print $report;
    };

    last unless $loop;

    TAEB->reset_state;

    print ' ';
    for (reverse 1..5) {
        print "\b$_";
        sleep 1;
    }
}

