DoctorKarma/lib/DoctorKarma/Config.pm

89 lines
2.1 KiB
Perl

package DoctorKarma::Config;
use v5.30.0;
use strict;
use warnings;
use Term::ReadLine;
use Const::Fast;
use JSON;
use Path::Tiny;
use DoctorKarma::Logger;
sub HOME { $ENV{HOME} }
sub CONFIG_DIR { "@{[HOME]}/.config/doctorkarma" }
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 logger {
my $self = shift;
if ( !defined $self->{logger} ) {
my $logger = DoctorKarma::Logger->new;
$self->{logger} = $logger;
}
return $self->{logger};
}
sub _config {
my $self = shift;
if ( !defined $self->{config} ) {
if ( !-f CONFIG_FILE ) {
$self->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 ) {
$self->logger->log_info(q(Config file not detected));
$self->_create_config_file;
}
}
sub _create_config_file {
my $self = shift;
my $logger = $self->logger;
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 $term = Term::ReadLine->new('Doctor Agustín');
my $token = $term->readline('Telegram token:');
my $config_contents = { telegram_token => $token };
$config_contents = encode_json($config_contents);
path(CONFIG_FILE)->spew_utf8($config_contents);
}
1;