#!/usr/bin/perl
use utf8;
use v5.22;

use File::Basename qw/ dirname basename /;
use File::Spec;
use Cwd qw/abs_path/;

our @INC;

BEGIN {
    push @INC, File::Spec->catdir( dirname( abs_path($0) ), '../lib' );
}

use Turnip;
use Pod::Usage;
use Log::Log4perl;
use YAML::XS qw(LoadFile);

my $logger = Log::Log4perl->get_logger("turnipctl");

binmode *STDOUT, ':utf8';

my $cfgfile;

if ( ( $ARGV[0] || '' ) eq '--conf' ) {
    shift @ARGV;
    $cfgfile = shift @ARGV;
}

Turnip->Initialize($cfgfile);

my $systemctlCmd = (grep -x, map File::Spec->catfile($_, 'systemctl'), split ":", $ENV{PATH})[0]
    or die "Failed to find systemctl path";

$logger->debug("systemctl exe = $systemctlCmd");

my $action = lc( shift @ARGV || 'help' );
$action =~ s/^--//;

my %actions = (
    help    => \&PrintUsage,
    start   => \&Start,
    stop    => \&Stop,
    restart => \&Restart,
    status  => \&Status,
    up      => \&Update,
    ls      => \&ListInstances
);

( $actions{$action} || \&UnknownAction )->(@ARGV);

sub UnknownAction {
    say "Uknown operation '$action' specified";
    PrintUsage();
}

sub PrintUsage {
    pod2usage( -verbose => 0 );
}

sub Start {
    systemctl( start => "turnip.target" );
}

sub Stop {
    systemctl( stop => "turnip.target" );
}

sub Restart {
    systemctl( restart => "turnip.target" );
}

sub Status {
    systemctl( "list-dependencies" => "turnip.target" );
}

sub Update {
    my $instance = shift;

    die "The instance name is required" unless $instance;

    $logger->debug("Setting new target: $instance");

    my $migration = Turnip->CreateMigrationPlan($instance);

    Turnip->SetTarget($instance);

    $logger->debug("Reloading systemd daemon configuration");

    systemctl('daemon-reload');

    for my $cmd ( 'stop', 'start' ) {
        my @stop = grep $migration->{$_} eq $cmd, keys %$migration;
        if (@stop) {
            $logger->debug( "Performing $cmd: " . join( " ", @stop ) );
            systemctl( $cmd, @stop );
        }
    }
}

sub Install {

}

sub ListInstances {
    say "Installed instances:";
    say " - $_" for Turnip->list;
}

sub RemoveInstance {

}

sub Prune {

}

sub systemctl {
    my @args = @_;
    ( system { $systemctlCmd } 'systemctl', @args ) == 0
      or die "Failed to execute systemctl @args: $?";
}

__END__

=pod

=head1 NAME

C<turnipctl> - Control and deploy container services

=head1 USAGE

=begin

turnipctl command [options]

=end

=head2 up {instance}

Updates configuration to the specified version and starts services. All unnecessary containers
will be stopped.

If the version isn't specified the latest will be used

=head2 install archive

Installs the new instance.

=head2 li

Lists all instances

=head2 ri instance [...]

Removes the specified instances

=head2 prune

Removes the unused service definitions

=cut
