#!/usr/bin/perl

use warnings;
use strict;

use constant CONFIG_DIR => '/var/lib/tarantool/started';
use constant PID_DIR    => '/var/run/tarantool';
use File::Spec::Functions 'catfile';
use File::Basename 'basename', 'dirname';
use IO::Socket::INET;

exit 0 unless -x PID_DIR;
exit 0 unless -x CONFIG_DIR;

for (glob catfile PID_DIR, '*.pid') {
    my $cfg = catfile CONFIG_DIR, basename $_, '.pid';

    unless(-r $cfg) {
        warn "Config file '$cfg' is not found\n";
        next;
    }

    my $admin_port;

    if (open my $fh, '<', $cfg) {
        my @cfg = <$fh>;
        ($admin_port) = grep /^\s*admin_port\s*=\s*\d+\s*$/, reverse @cfg;
    } else {
        warn "$!\n";
        next;
    }

    unless($admin_port) {
        warn "admin_port is not found in $cfg\n";
        next;
    }

    $admin_port =~ s/\D+//g;

    my $socket = IO::Socket::INET->new(PeerAddr => "localhost:$admin_port");
    unless($socket) {
        warn "Can't connect to localhost:$admin_port: $!";
        next;
    }



    my $logger_pid;
    local $SIG{ALRM} = sub { die "alarm\n" };
    alarm 3;

    eval {
        print $socket "show info\n";
        while(<$socket>) {
            next unless /^\s*logger_pid:\s*(\d+)\s*$/;
            $logger_pid = $1;
            last;
        }
    };

    alarm 0;

    unless($logger_pid) {
        warn "Can't define logger_pid\n";
        next;
    }

    unless(kill 'HUP' => $logger_pid) {
        warn "Can't send HUP to pid=$logger_pid: $!";
        next;
    }
}

=head1 NAME

/usr/lib/tarantool/tarantool_logrotate - utility to rotate
tarantool instances logs


=head1 SINOPSYS

    tarantool_logrotate

=head1 DESCRIPTION

The utility tries to connect to each running tarantool instance to get
logger pid file, then it sends B<SIGHUP> to logger which initiates
log rotataion procedure.
