DoctorKarma/lib/DoctorAgustin/Config.pm

73 lines
1.6 KiB
Perl

package DoctorAgustin::Config;
use v5.30.0;
use strict;
use warnings;
use Term::ReadLine;
use Const::Fast;
use JSON;
sub HOME { $ENV{HOME} }
sub CONFIG_DIR {"@{[HOME]}/.config/doctoragustin" }
sub CONFIG_FILE { "@{[CONFIG_DIR]}/config.json" }
sub new {
my $class = shift;
my $self = bless {}, $class;
$self->_create_config_file_if_not_exists;
return $self;
}
sub config {
my $self = shift;
if (!defined $self->{config}) {
if (! -f CONFIG_FILE ) {
$logger->log_error(qq(@{CONFIG_FILE]} is not a plain file, unable to read config.));
die;
}
my $config = decode_json(path(CONFIG_FILE)->slurp_utf8)
$self->{config} = $config;
}
return $self->{config};
}
sub telegram_token {
my $self = shift;
if (!defined $self->{telegram_token}) {
my $config = $self->config;
$self->{telegram_token} = $config->{telegram_token};
}
return $self->{telegram_token};
}
sub _create_config_file_if_not_exists {
my $self = shift;
if (! -e CONFIG_FILE ) {
$logger->log_info(q(Config file not detected));
$self->create_config_file;
}
}
sub _create_config_file {
if (! -e CONFIG_DIR ) {
$logger->log_info(qq(Creating @{[CONFIG_DIR]}));
eval {
path(CONFIG_DIR)->mkpath;
};
if ($@) {
$logger->log_error(qq(Unable to create directory @{[CONFIG_DIR]}: $@));
die;
}
}
my $token = $term->readline('Telegram token:');
my $config_contents = { token => $token };
$config_contents = encode_json ($config_contents);
path($CONFIG_FILE)->spew_utf8($config_contents);
}
1;