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

# /bsta/v
# viewer is generated from viewer.1.pl.
#
# The viewer interface
#
# Copyright (C) 2016, 2017, 2019, 2020, 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_header_env',
	'read_data_file', 'write_data_file',
	'url_query_decode',
	'join_path',
	'open_encoded'
);
use bsta_lib (
	'STATE', 'TEXT_MODE', 'INTF_STATE',
	'fail_method', 'fail_content_type',
	'get_remote_addr', 'get_frame', 'get_password',
	'merge_settings',
	'print_viewer_page', 'write_index',
	'ong'
);

###PERL_PATH_SEPARATOR:     PATH_SEPARATOR     = /

###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_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 %frame_data;
my %next_frame_data;
my %default;
my %settings;
my %state;
my %new_state;
my %goto_list;
my %words_data;

my $method;
my $frame;
my $frame_data_path;
my $next_frame_data_path;
my $password;
my $password_ok;
my $IP;
my $access;
my $timer;
my $timer_unlocked;
my $fh;
my $show_command;
my $ongtime;
my $text_mode;
my $words_page;
my $words_data_path;

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

$IP = get_remote_addr();
$frame = get_frame(\%cgi);
$password = get_password(\%cgi);

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

if ($frame >= 0) {
	$frame_data_path = join_path(PATH_SEPARATOR(), DATA_PATH(), $frame);
	%frame_data= read_data_file($frame_data_path);
}

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

# state & activation logic
if (open_encoded($fh, "+<:encoding(UTF-8)", DATA_STATE_PATH())) {
	if (flock($fh, 2)) {
		
		%state = read_data_file($fh);
		
		if ($frame < 0) {
			$frame = int($state{'last'}) + $frame +1;
			$frame_data_path = join_path(PATH_SEPARATOR(), DATA_PATH(), $frame);
			%frame_data = read_data_file($frame_data_path);
		}
		
		if (
			(int($state{'state'}) == STATE->{'waiting'}) &&
			($frame == int($state{'last'})) &&
			($method ne 'HEAD') &&
			(!$password_ok)
		) {
			# register IP for progress
			my %new_state = %state;
			unless (
				($state{'ip1'} eq $IP) ||
				($state{'ip2'} eq $IP) ||
				($state{'ip3'} eq $IP)
			)
			{
				if ($state{'ip1'} eq '') {
					$new_state{'ip1'} = $IP;
				}
				elsif ($state{'ip2'} eq '') {
					$new_state{'ip2'} = $IP;
				}
				elsif ($state{'ip3'} eq '') {
					$new_state{'ip3'} = $IP;
					$new_state{'state'} = STATE->{'ready'};
				}
				else {
					$new_state{'state'} = STATE->{'ready'};
				}
				write_data_file($fh, \%new_state);
			}
		}
		elsif (
			(int($state{'state'}) == STATE->{'inactive'}) &&
			($frame == 1)
		) {
			# ready to activate?
			# NOTE: at this point frame 0 is already ONGed.
			my %story;
			my $ong_time = int($settings{'firstongtime'});
			my $r;
			
			%story     = read_data_file(DATA_STORY_PATH());
			
			if (
				(int($story{'state'}) == INTF_STATE->{'>|'} ) &&
				(int($story{'pass'}) == 1)
			) {
				# conditions met; ACTIVATE!
				
				# set initial state
				$state{'state'} = STATE->{'waiting'};
				$state{'last'}  = 1; 
				$state{'ip1'}   = '0.0.0.0';
				$state{'ip2'}   = '0.0.0.0';
				$state{'ip3'}   = '';
				$state{'nextong'} = (int($time / 3600) + int($settings{'firstongtime'})) * 3600 ;
				$state{'ongtime'} = $ong_time;
				
				# prepare to ONG frame 1
				
				$r = ong(
					1,         # frame ID
					$time,     # ONG time,
					$ong_time, # timer
					0,         # update
					0,         # print
					\%settings,
					\%default,
					\%frame_data,
					''         # %goto_list
				);
				if ($r) {
					$r = write_index(\%state, \%settings);
				}
				if ($r) {
					$r = write_data_file($fh, \%state);
				}
				unless ($r) {
					# FAILED ONG! Story as if it was inactive!
					$state{'state'} = STATE->{'inactive'};
				}
			}
		}
	}
	else {
		# FAILED GET STATE! Story as if it was inactive!
		$state{'state'} = STATE->{'inactive'};
	}
	close ($fh);
}
else {
	$state{'state'} = STATE->{'inactive'};
}

$next_frame_data_path = join_path(PATH_SEPARATOR(), DATA_PATH(), $frame+1);
%next_frame_data = read_data_file($next_frame_data_path);

# apply defaults
%frame_data      = merge_settings(\%default,      \%frame_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));
if ($state{'state'} >= STATE->{'ready'}) {
	$timer_unlocked = 3;
}
elsif ($state{'ip3'} ne '') {
	$timer_unlocked = 3;
}
elsif ($state{'ip2'} ne '') {
	$timer_unlocked = 2;
}
elsif ($state{'ip1'} ne '') {
	$timer_unlocked = 1;
}
else {
	$timer_unlocked = 0;
}

if (
		$password_ok || (
			(int($state{'state'}) >= STATE->{'waiting'}) &&
			($frame <= int($state{'last'})) &&
			($frame >= 0)
		)
	) {
	$access = 1;
}
else {
	$access = 0;
	# replace frame data with fail state replacement
	%frame_data = read_data_file(DATA_NOACCESS_PATH());
	%frame_data = merge_settings(\%default, \%frame_data);
}

$text_mode = int($cgi{'b'});
if($text_mode > TEXT_MODE->{'words'}) {
	$text_mode = TEXT_MODE->{'normal'};
}
$words_page = int($cgi{'i'});

$words_data_path = join_path(PATH_SEPARATOR(), DATA_WORDS_PATH(), $frame);
%words_data = read_data_file(
	$words_data_path, # file
	'', # encoding
	0,  # no header
	($text_mode != TEXT_MODE->{'words'}), # header only
	1,  # as list
);

print "Content-type: text/html\n";
if(!$access) {
	print "Status: 403 Forbidden\n";
}
print "\n";
if($method eq 'HEAD') {
	exit;
}

print_viewer_page (
	\*STDOUT,
	{
		'launch'        => 0,
		'frame'         => $frame,
		'access'        => $access,
		'password_ok'   => $password_ok,
		'timer_unlocked'=> $timer_unlocked,
		'timer'         => $timer,
		'static'        => 0,
		'show_command'  => $show_command,
		'text_mode'     => $text_mode,
		'words_page'    => $words_page
	},
	\%state,
	\%settings,
	\%frame_data,
	\%next_frame_data,
	\%words_data,
);
