###RUN_PERL: #!/usr/bin/perl

# update.pl is generated from update.1.pl.
#
# update already ONGed frames & stuff
#
# Copyright (C) 2016, 2017, 2023, 2024  Balthasar Szczepański
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

use strict;
use utf8;
use Encode::Locale ('decode_argv');
use Encode ('encode', 'decode');

###PERL_LIB: use lib /botm/lib/bsta
use botm_common (
	'read_data_file'
);
use bsta_lib (
	'STATE',
	'ong'
);

###PERL_DATA_DEFAULT_PATH:  DATA_DEFAULT_PATH  = /botm/data/bsta/default
###PERL_DATA_SETTINGS_PATH: DATA_SETTINGS_PATH = /botm/data/bsta/settings
###PERL_DATA_STATE_PATH:    DATA_STATE_PATH    = /botm/data/bsta/state

binmode STDIN,  ':encoding(UTF-8)';
binmode STDOUT, ':encoding(UTF-8)';
binmode STDERR, ':encoding(UTF-8)';
decode_argv();

my $time = time();
srand ($time-$$);

my %settings  = read_data_file(DATA_SETTINGS_PATH());
my %default   = read_data_file(DATA_DEFAULT_PATH());
my %state     = read_data_file(DATA_STATE_PATH());

my $ong_state  = int($state{'state'});
my $last_frame = ($ong_state > STATE->{'inactive'}) ? 
	int($state{'last'}) :
	0;

my @list;

my $fail = 0;

print $time."\n";

foreach my $id (@ARGV) {
	if ($id eq 'all') {
		push @list, 'i';
		push @list, 'c';
		for (my $f=0; $f<=$last_frame; $f+=1) {
			push @list, $f;
		}
	}
	elsif ($id =~ /^[0-9]+$/) {
		my $f = int($&);
		if ($f <= $last_frame) {
			push @list, $f
		}
		else {
			print "$f > $last_frame\n";
			$fail += 1;
		}
	}
	elsif ($id =~ /^[ic]$/) {
		push @list, $&;
	}
	else {
		print "$id ???\n";
		$fail += 1;
	}
}

foreach my $id (@list) {
	print "ONG $id\n";
	my $r = ong(
		$id,   # frame ID
		$time, # ONG time
		'',    # timer value; not relevant
		1,     # update
		1,     # print
		\%settings,
		\%default,
		'',    # %frame_data
		''    # %goto_list
	);
	unless ($r) {
		$fail += 1;
		print "ONG FAIL!\n";
	}
}
print "\n";

exit $fail;
