package SLUB::LZA::Rosetta::TA::Command::init;
use SLUB::LZA::Rosetta::TA -command;
use strict;
use warnings;
use YAML qw(DumpFile);
use feature qw(say);
use IO::Prompt::Tiny qw/prompt/;
use Crypt::Mode::CBC;
use Path::Tiny;
use namespace::autoclean;



# VERSION

# ABSTRACT: init module for ta-tool

sub abstract {"Initialize $0";}
sub description {"Initialize $0, preparing config"}
sub opt_spec {
    return(
        ["verbose|v" => "enable verbose output"],
        ["rosettahost|r=s" => "host adress where Rosetta runs", {required=>1}],
        ["logdir|l=s" => "logdir where rosetta stores it server log files", {required=>1}],
        ["authentication|a" => "enable authentification (needed if Rosetta's general parameter 'sru_authentication=true'), password is stored salted only in config file!"],
        ["httponly" => "with this flag only HTTP (instead HTTPS) is used"],
    );
}
sub validate_args {
    my ($self, $opt, $args) = @_;
    # no args allowed but options!
    $self->usage_error("No args allowed") if @$args;
}

sub execute {
    my ($self, $opt, $args) = @_;
    my %config;
    $config{host} = $opt->{rosettahost};
    $config{logdir} = $opt->{logdir};
    $config{httponly} = $opt->{httponly};
    if (defined $opt->{authentication}) {
        warn "HINT: The password will stored in config file!";
        my $user = prompt('User:' );
        $config{user} = "$user";
        my $institution = prompt('Institution:' );
        $config{institution} = "$institution";
        RETRY:
        my $passwd1 = prompt ('Password:', -echo=>"*");
        my $passwd2 = prompt ('Password, again:', -echo=>"*");
        if ($passwd1 ne $passwd2) {
            say "you typed different passwords, retry";
            goto RETRY;
        }
        $config{password} = SLUB::LZA::Rosetta::TA::Crypt::encrypt("$passwd1");
    }
    if (defined $SLUB::LZA::Rosetta::TA::config_file) {
        if (defined $opt->{verbose}) {
            say "store config in $SLUB::LZA::Rosetta::TA::config_file";
        }
        my $file = path($SLUB::LZA::Rosetta::TA::config_file);
        $file->touch();
        $file->chmod("0600");
        my $fh = path($SLUB::LZA::Rosetta::TA::config_file)->filehandle({exclusive => 0}, ">");
        YAML::DumpFile($fh, %config);
        $fh->close;
    }
}

1;
