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

# reset is generated from reset.1.pl.
#
# Reset BSTA state
#
# Copyright (C) 2016 - 2018, 2023  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', 'write_data_file',
);
use bsta_lib (
	'STATE', 'INTF_STATE',
	'write_index'
);

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

###PERL_DATA_CHAT_PATH:     DATA_CHAT_PATH     = /botm/data/bsta/chat
###PERL_DATA_SETTINGS_PATH: DATA_SETTINGS_PATH = /botm/data/bsta/state
###PERL_DATA_STATE_PATH:    DATA_STATE_PATH    = /botm/data/bsta/state
###PERL_DATA_STORY_PATH:    DATA_STORY_PATH    = /botm/data/bsta/story

###PERL_RESET_PASSWORD:     RESET_PASSWORD     = ''

my %story;
my %state;
my %chat;
my %settings;

delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
###PERL_SET_PATH: $ENV{'PATH'} = /usr/local/bin:/usr/bin:/bin;

%settings = read_data_file(DATA_SETTINGS_PATH());
unless (
	($ARGV[0] ne '') && (
		($ARGV[0] eq $settings{'password'}) ||
		($ARGV[0] eq RESET_PASSWORD())
	)
) {
	print STDERR "Wrong password; no reset.\n";
	exit 1;
}

%state = (
	'state' => STATE->{'inactive'},
	'last'  => 0,
	'ongtime' => '',
	'nextong' => '',
	'ip1' => '',
	'ip2' => '',
	'ip3' => ''
);
%story = (
	'id'      => 0,
	'letter'  => '',
	'lastip'  => '0.0.0.0',
	'content' => '',
	'pass'    => 0,
	'state'   => INTF_STATE->{'X'}
);
%chat = (
	'id'      => 0,
	'state'   => 0, # TODO chat state enum?
	'content' => ''
);

write_data_file(DATA_STATE_PATH(), '', '', \%state);
write_data_file(DATA_STORY_PATH(), '', '', \%story);
write_data_file(DATA_CHAT_PATH() , '', '', \%chat);

write_index(
	\%state,
	\%settings,
	$story{'pass'},
	$story{'state'},
	0 # pause
);
