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

# /bsta/i
# info.pl is generated from info.1.pl.
#
# The frame/story info interface
#
# Copyright (C) 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 (
	'HTTP_STATUS',
	'http_header_status',
	'read_header_env',
	'read_data_file', 'write_data_file',
	'url_query_decode',
	'join_path'
);
use bsta_lib (
	'STATE',
	'fail_method', 'fail_content_type',
	'get_password',
	'merge_settings'
);

###PERL_PATH_SEPARATOR:     PATH_SEPARATOR     = /

###PERL_DATA_PATH:          DATA_PATH          = /botm/data/bsta
###PERL_DATA_ATTACH_PATH:   DATA_ATTACH_PATH   = /botm/data/bsta/a
###PERL_DATA_DEFAULT_PATH:  DATA_DEFAULT_PATH  = /botm/data/bsta/default
###PERL_DATA_NOACCESS_PATH: DATA_NOACCESS_PATH = /botm/data/bsta/noaccess
###PERL_DATA_SETTINGS_PATH: DATA_SETTINGS_PATH = /botm/data/bsta/settings
###PERL_DATA_STATE_PATH:    DATA_STATE_PATH    = /botm/data/bsta/state
###PERL_DATA_WORDS_PATH:    DATA_WORDS_PATH    = /botm/data/bsta/words/

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

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

my %http;
my %cgi;
my %info_data;
my %next_frame_data;
my %default;
my %settings;
my %state;

my $method;
my $frame = '';
my $attachment = '';
my $words = '';
my $password;
my $password_ok;
my $access;
my $show_command;
my $ongtime;
my $timer;
my $info_data_path;
my $next_frame_data_path;
my $ong_state;
my $last_frame;

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

if ($ENV{'REQUEST_METHOD'} =~ /^(HEAD|GET|POST)$/) {
	$method = $1;
}
else{
	exit fail_method($ENV{'REQUEST_METHOD'}, ['GET', 'POST', 'HEAD']);
}

%http = read_header_env(\%ENV);
%cgi = url_query_decode($ENV{'QUERY_STRING'});

if ($method eq 'POST') {
	if ($http{'content-type'} eq 'application/x-www-form-urlencoded') {
		my %cgi_post = url_query_decode( <STDIN> );
		%cgi = merge_settings(\%cgi, \%cgi_post);
	}
	# multipart not supported
	else{
		exit fail_content_type($method, $http{'content-type'});
	}
}

if ($cgi{'f'} =~ /^.+$/) {
	$frame = int($&);
}
elsif ($cgi{'a'} =~ /^.+$/) {
	$attachment = int($&);
}
elsif ($cgi{'i'} =~ /^.+$/) {
	$attachment = int($&);
}
elsif ($cgi{'w'} =~ /^.+$/) {
	$words = $&;
}
elsif ($ENV{'PATH_INFO'} =~ /^\/a(.+)$/) {
	$attachment = int($1);
}
elsif ($ENV{'PATH_INFO'} =~ /^\/w(.+)$/) {
	$words = $1;
}
elsif ($ENV{'PATH_INFO'} =~ /^\/f?(.+)$/) {
	$frame = int($1);
}

$password = get_password(\%cgi);

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

$ong_state  = int($state{'state'});
$last_frame = int($state{'last'});

$password_ok = ($password eq $settings{'password'});

# comment info, not frame
if ($words ne '') {
	$info_data_path = join_path(PATH_SEPARATOR(), DATA_WORDS_PATH(), $words);
	%info_data      = read_data_file($info_data_path);
	if ($words =~ /^[0-9]+$/) {
		$frame = int($&);
		if ($info_data{'posts'} eq '') {
			$info_data{'posts'} = 0;
		}
	}
	else {
		$frame = ($info_data{'frame'} ne '') ? int($info_data{'frame'}) : -1;
		unless ($password_ok) {
			delete($info_data{'password'});
			delete($info_data{'key'});
		}
	}
}
# attachment info, not frame
elsif ($attachment ne '') {
	%info_data = read_data_file(DATA_ATTACH_PATH().$attachment);
	$frame = ($info_data{'frame'} ne '') ? int($info_data{'frame'}) : -1;
}
# frame info
elsif ($frame ne '') {
	if ($frame < 0) {
		$frame = $last_frame + $frame +1;
	}
	$info_data_path       = join_path(PATH_SEPARATOR(), DATA_PATH(), $frame);
	$next_frame_data_path = join_path(PATH_SEPARATOR(), DATA_PATH(), $frame+1);
	%info_data       = read_data_file($info_data_path);
	%next_frame_data = read_data_file($next_frame_data_path);
	%info_data       = merge_settings(\%default,      \%info_data);
	%next_frame_data = merge_settings(\%default, \%next_frame_data);
	
	$timer   = int($state{'nextong'}) - $time;
	$ongtime = int($state{'ongtime'});
	if($ongtime == 0) {
		$ongtime = int($settings{'ongtime'})
	}
	$show_command = ($timer < ($ongtime * 3600 / 3));
}
# state info, not frame
else {
	unless ($password_ok) {
		# just show if IP was saved, not its value
		if ($state{'ip1'} ne '') {
			$state{'ip1'} = 1;
		}
		if ($state{'ip2'} ne '') {
			$state{'ip2'} = 1;
		}
		if ($state{'ip3'} ne '') {
			$state{'ip3'} = 1;
		}
	}
	print "Content-type: text/plain; charset=UTF-8\n\n";
	if ($method eq 'HEAD') {
		exit;
	}
	write_data_file(
		\*STDOUT, \%state, '',
		0, 0, 0,
		'>>', 1
	);
	
	exit;
}

if (
	$password_ok || (
		($ong_state >= STATE->{'waiting'}) &&
		($frame <= $last_frame) &&
		($frame >= 0)
	)
) {
	$access = 1;
	
	if (
		($words eq '') &&
		($attachment eq '') &&
		($info_data{'command'} eq '') && (
			$password_ok ||
			($frame < $last_frame) || (
				($ong_state >= STATE->{'ready'}) &&
				$show_command
			)
		)
	) {
		$info_data{'command'} = $next_frame_data{'title'};
	}
}
else {
	$access = 0;
	if (($attachment ne '') || ($words ne '')) {
		%info_data = ();
	}
	else {
		%info_data = read_data_file(DATA_NOACCESS_PATH());
		%info_data = merge_settings(\%default, \%info_data);
	}
}
if (
	($attachment eq '') &&
	($words eq '')
) {
	if ($info_data{'frame'} eq '') {
		$info_data{'frame'} = sprintf($settings{'frame'}, $frame, $info_data{'ext'});
	}
	if ($info_data{'page'} eq '') {
		unless (($access) && ($frame < $last_frame)) {
			$info_data{'page'} = '';
		}
		elsif ($frame == 0) {
			$info_data{'page'} = 'index.htm';
		}
		else {
			$info_data{'page'} = sprintf($settings{'frame'}, $frame, 'htm');
		}
	}
}

print "Content-type: text/plain; charset=UTF-8\n";
if (!$access) {
	print http_header_status(HTTP_STATUS->{'forbidden'});
}
print "\n";
if($method eq 'HEAD') {
	exit;
}
write_data_file(
	\*STDOUT, \%info_data, '',
	0, 0, 0,
	'>>', 1
);
