<?php 

$removing = false;
if (count($argv) == 2) {
    $tag = $argv[1];
    $removing = true;
}
else if (count($argv) == 5) {
    $hostname = $argv[1];
    $port = $argv[2];
    $tag = $argv[3];
    $file = $argv[4];
}
else {
    die();
}

$get_spool_dir = 'ls -d /var/lib/rsyslog || ls -d /var/spool/rsyslog';
$spool_directory = exec($get_spool_dir, $out, $rc);
if ($rc == 2) {
    $spool_directory = '/var/spool/rsyslog';
    mkdir($spool_directory);
}

$conf_dir = '/etc/rsyslog.d';
if (!is_dir($conf_dir)) {
    mkdir($conf_dir);
}

# Only valid hostnames
if (!preg_match("/^[a-zA-Z0-9.-]*$/", $hostname)) {
    echo "Error: Invalid characters in hostname.";
    exit(1);
}

# Only integers allowed
if (!preg_match("/^[0-9]*$/", $port)) {
    echo "Error: Invalid characters in port. Only integers allowed.";
    exit(1);
}

# POSIX portable file name character set
if (!preg_match("/^[\w.-]*$/", $tag)) {
    echo "Error: Invalid characters in tag.";
    exit(1);
}
if (!preg_match("/^[\w.-\/]*$/", $file)) {
    echo "Error: Invalid characters in file.";
    exit(1);
}

$conf_file = $conf_dir . '/nagiosxi-'.$tag.'.conf';

if ($removing) {
    @unlink($conf_file);
    finish();
}

$file_content = '
# Automatically generated by Nagios XI. Do not edit this file!

$ModLoad imfile
$InputFilePollInterval 10
$PrivDropToGroup adm
$WorkDirectory '.$spool_directory.'

# Input for '.$file.'
$InputFileName '.$file.'
$InputFileTag '.$tag.':
$InputFileStateFile nls-state-'.uniqid().' # Must be unique for each file being polled
# Uncomment the folowing line to override the default severity for messages
# from this file.
#$InputFileSeverity info
$InputFilePersistStateInterval 20000
$InputRunFileMonitor

# Forward to Nagios Logserver and then discard.
if $programname == \'' . $tag . '\' then @@' . $hostname . ':' . $port . '
if $programname == \'' . $tag . '\' then ~';

file_put_contents($conf_file, $file_content);

finish();

function finish() {
    //restart rsyslogd
    $cmdline = "service rsyslog restart";
    echo exec($cmdline, $out, $rc);

    exit($rc);
}
