#!/usr/bin/env perl

# Copyright 2019 Imply Data, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

use strict;
use warnings;

# Set MAX_LINE_LEN as line length for svlogd because the default value is
# 1000 which is too small for Druid logs.
# MAX_BUF_LEN must be greater than MAX_LINE_LEN according the man page of
# svlogd.
# Reference: http://manpages.ubuntu.com/manpages/bionic/man8/svlogd.8.html
use constant MAX_LINE_LEN => 10000;
use constant MAX_BUF_LEN => 10240;

sub logdie($)
{
  my ($msg) = @_;
  chomp $msg;
  die "[" . (scalar localtime()) . "] $msg\n";
}

if (@ARGV < 3) {
  die "need at least 3 arguments\n";
}

my ($svlogd, $logdir, $command) = @ARGV;

open STDOUT, "|-", "$svlogd", "-l", MAX_LINE_LEN, "-b", MAX_BUF_LEN, "$logdir" or logdie "pipe to $svlogd $logdir failed: $!\n";
open STDERR, ">&STDOUT" or logdie "redirecting stderr failed: $!\n";
exec('sh', '-c', "exec $command") or logdie "exec [$command] failed: $!";
