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

# /bsta/g
# goto is generated from goto.1.pl.
#
# The frame list
#
# 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 (
	'fail_method', 'fail_content_type',
	'redirect',
	'read_header_env',
	'url_query_decode',
	'_x_encoded'
);
use bsta_lib (
	'STATE',
	'get_password',
	'print_goto',
	'merge_settings',
	'read_settings', 'read_state', 'read_goto'
);

###PERL_CGI_PATH:           CGI_PATH           = /bsta/
###PERL_CGI_LIST_PATH:      CGI_LIST_PATH      = /bsta/goto.htm
###PERL_CGI_VIEWER_PATH:    CGI_VIEWER_PATH    = /bsta/v

###PERL_WWW_GOTO_PATH:      WWW_GOTO_PATH      = /botm/www/1190/bsta/goto.htm

###PERL_WEBSITE_NAME:       WEBSITE_NAME       = Bicycles on the Moon

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

my $method;
my $password;
my $password_ok;
my $no_cgi;

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

$no_cgi = (scalar (keys %cgi) == 0);

if ($no_cgi) {
	if (_x_encoded('-f', WWW_GOTO_PATH())) {
		exit redirect($method, CGI_LIST_PATH());
	}
}

$password = get_password(\%cgi);

%settings  = read_settings();
%state     = read_state();
%goto_list = read_goto();

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

print "Content-type: text/html; charset=UTF-8\n";
print "\n";
if($method eq 'HEAD') {
	exit;
}

print_goto(
	\*STDOUT,
	\%state,
	\%settings,
	\%goto_list,
	$password_ok
);
