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

# /bsta/f
# viewer.pl is generated from viewer.1.pl.
#
# The frame interface
#
# Copyright (C) 2016, 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',
	'read_header_env',
	'url_query_decode',
	'read_data_file',
	'join_path',
	'merge_url',
	'open_encoded', 'stat_encoded',
	'http_header_line', 'http_header_content_length', 'http_header_content_disposition'
);
use bsta_lib (
	'STATE', 'INTF_STATE',
	'fail_method', 'fail_content_type', 'fail_open_file', 'fail_500', 'redirect',
	'get_frame', 'get_password',
	'merge_settings'
);

###PERL_PATH_SEPARATOR:     PATH_SEPARATOR     = /

###PERL_CGI_PATH:           CGI_PATH           = /bsta/

###PERL_DATA_PATH:          DATA_PATH          = /botm/data/bsta
###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_STORY_PATH:    DATA_STORY_PATH    = /botm/data/bsta/story

###PERL_WWW_PATH:           WWW_PATH           = /botm/www/1190/bsta/

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 %frame_data;
my %default;
my %settings;
my %state;

my $method;
my $frame;
my $password;
my $password_ok;
my $IP;
my $access;
my $try_onged;
my $frame_path;
my $frame_data_path;
my $frame_file;
my $fh;
my $buffer;
my $ong_state;
my $last_frame;
my $r = 0;

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'});
	}
}

$frame    = get_frame(\%cgi);
$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'});

if ($frame < 0) {
	$frame = $state{'last'} + $frame +1;
}

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

$access = 0;
if (
		$password_ok || (
			($ong_state >= STATE->{'waiting'}) &&
			($frame <= $last_frame) &&
			($frame >= 0)
		)
	) {
	$access = 1;
}
elsif (
	($ong_state == STATE->{'inactive'}) &&
	($frame == 0)
) {
	my %story = read_data_file(DATA_STORY_PATH());
	if (
		(int($story{'pass'}) == 1) &&
		(int($story{'state'}) == INTF_STATE->{'>|'})
	) {
		$access = 1;
	}
}

$try_onged = (
	(!$access) || (
		($frame <= $last_frame) &&
		($ong_state > STATE->{'inactive'})
	)
);

if ($access) {
	$frame_data_path = join_path(PATH_SEPARATOR(), DATA_PATH(), $frame);
	%frame_data = read_data_file($frame_data_path);
	%frame_data = merge_settings(\%default, \%frame_data);
}
else {
	%frame_data = read_data_file(DATA_NOACCESS_PATH());
	%frame_data = merge_settings(\%default, \%frame_data);
}
if ($frame_data{'frame'} ne '') {
	$frame_file = $frame_data{'frame'};
}
else {
	$frame_file = sprintf(
		$settings{'frame'},
		$frame, $frame_data{'ext'}
	);
}

if ($try_onged) {
	$frame_path = join_path(PATH_SEPARATOR(), WWW_PATH(), $frame_file);
	$r = open_encoded($fh, '<' , $frame_path);
	if ($r) {
		close($r);
		$frame_path = merge_url(
			{'path' => CGI_PATH()},
			{'path' => $frame_file}
		);
		exit redirect ($method, $frame_path, HTTP_STATUS->{'see_other'});
	}
}
unless ($r) {
	$frame_path = join_path(PATH_SEPARATOR(), DATA_PATH(), $frame_file);
	$r = open_encoded($fh, '<' , $frame_path);
	unless ($r) {
		exit fail_open_file($method, 'image file', $frame_file);
	}
}
unless (binmode($fh)) {
	close($fh);
	exit fail_500("Can't switch file to binary mode.");
}

if (my @file_info = stat_encoded($frame_path)){
	print http_header_content_length($file_info[7]);
}
if ($frame_data{'content-type'} ne '') {
	print http_header_line('content-type', $frame_data{'content-type'});
}
if ($frame_file ne '') {
	print http_header_content_disposition('inline', $frame_file);
}
unless (binmode STDOUT) {
	close($fh);
	exit fail_500("Can't switch output to binary mode.");
}
print "\n";

if($method ne 'HEAD'){
	while (read ($fh, $buffer, 1024)) {
		print (STDOUT $buffer);
	}
}
close($fh);
