#!perl -w

use strict;
use warnings;

use Rex;
use Rex::Config;
use Rex::Logger;
use Rex::Agent;

use Getopt::Std;

$|++;

my %opts;

getopts('rfvhdp:s:u:g:P:i:t:c:', \%opts);

$Rex::Logger::debug = $opts{'d'};

if($opts{'l'}) {
   Rex::Config->set_log_filename($opts{'l'});
}

Rex::Logger::debug("Command Line Parameters");
for my $param (keys %opts) {
   Rex::Logger::debug("\t$param = " . $opts{$param});
}

if($opts{'h'}) {
   print "(R)?ex - (Remote)? Execution (Agent)\n";
   printf "  %-15s %s\n", "-r", "Run it. This is alpha code. Don't use it unless you want to test it. But be warned, it may crash everything.";
   printf "  %-15s %s\n", "-l", "Set Logfilename";
   printf "  %-15s %s\n", "-s server", "(R)?ex Master Server (default: rex)";
   printf "  %-15s %s\n", "-p port", "(R)?ex Master Server Port (default: 7345)";
   printf "  %-15s %s\n", "-P pid-file", "Pid File (default: /var/run/rex-agent.pid)";
   printf "  %-15s %s\n", "-c cache-dir", "Directory where to cache the rexfiles. (default: /var/cache/rex-agent)";
   printf "  %-15s %s\n", "-u user", "User Rex-Agent should switch to. (default: root)";
   printf "  %-15s %s\n", "-g group", "Group Rex-Agent should switch to. (default: root)";
   printf "  %-15s %s\n", "-i interval", "Interval to check for new configuration settings in seconds. (default: 1300)";
   printf "  %-15s %s\n", "-t timeout", "Connection timeout in seconds. (default: 10)";
   printf "  %-15s %s\n", "-f", "Run in foreground.";
   printf "  %-15s %s\n", "-d", "Debug";
   printf "  %-15s %s\n", "-v", "Display version";
   print "\n";
   CORE::exit 0;
} elsif($opts{'v'}) {
   print "(R)?ex (Agent) " . $Rex::VERSION . "\n";
   CORE::exit 0;
}

if(!$opts{'r'}) {
   print "This is alpha code. Don't use it unless you want to test it. But be warned, it may crash everything.\n";
   CORE::exit 1;
}

Rex::Agent->run_now(
   user => $opts{'u'}     || 'root',
   group => $opts{'g'}    || 'root',
   pid_file => $opts{'P'} || '/var/run/rex-agent.pid',
   interval => $opts{'i'} || 1300,
   port => $opts{'p'}     || 7345,
   server => $opts{'s'}   || 'rex',
   daemon => defined $opts{'f'}?0:1,
   timeout => $opts{'t'}  || 10,
   cache_dir => $opts{'c'} || '/var/cache/rex-agent',
);

