#!/usr/bin/perl

# (c) 2016 Bruker BioSpin GmbH

use strict;
use English;
use Getopt::Long;
use Pod::Usage;
use Sys::Syslog qw(:standard :macros); # standard functions & macros
use File::Basename;

my $program = basename ($0);

die "Only root may run $program\n" unless $EFFECTIVE_USER_ID == 0;

##
# Subroutines
sub editYumConf;
sub boolean($) {my $var=shift; return $var ? 'true' : 'false'; }

###
# Supported options
my $verbose = 0;
my $syslog = 1;
my $help = 0;
my $man = 0;

GetOptions(
	'help|?' => \$help,
	'man' => \$man,
	'verbose+' => \$verbose,
	'syslog!' => \$syslog,
	) || pod2usage(2);
pod2usage(1) if $help;
pod2usage(-exitstatus => 0, -verbose => 2) if $man; 

if ($verbose)
{
  print "\nFlags:\n";
  print ' $help    '," = ",boolean($help),"\n";
  print ' $man     '," = ",boolean($man),"\n";
  print ' $verbose '," = ",boolean($verbose),"\n";
  print "\n";
}

###
# Use syslog for reports
openlog('bruker-setup', 'nofatal,pid', 'user');

syslog(LOG_INFO,"Execute $program");
editYumConf();

closelog();

exit;

sub editYumConf()
{
    # Path to yum config file
    my $yumconf = '/etc/yum.conf';
    # define info and error message
    my $errmsg = "Edit installonly_limit value in $yumconf";
    syslog(LOG_INFO, $errmsg);
    print STDOUT $errmsg,"\n" if $verbose;
    # open yum config
    if( !open(YUMCONF,"<$yumconf") )
    {
      # print message in case of file open error
      $errmsg = "Failed to open $yumconf";
      syslog(LOG_ERR, $errmsg);
      print STDERR $errmsg,"\n" if $verbose;
    } else {
        # define boolean value which stores if the config file contains the search string
	my $hit = 0;
        # loop over each line in file
	while (<YUMCONF>) {
          # check hit
	  if ($_ =~ /^installonly_limit/) {
		$hit = 1;
		last;
	  }
	}
        # close file handler
	close(YUMCONF);
        # evaluate matching
	if ($hit) {
          # config file contains line, we use sed for the exchange
	  system("sed -i.bak -e s/^installonly_limit[[:space:]]*=[[:space:]]*[0-9]*/installonly_limit=4/ $yumconf");
	  if ($? == -1) {
            # give feedback, if system call produces an error 
	    $errmsg = "command failed: $!";
            syslog(LOG_ERR, $errmsg);
	    print STDERR $errmsg,"\n" if $verbose;
	  }
	} else {
          # config file does not contain the key. Set the key after the start of the main section
          system("sed -i.bak -e s/\[main\]/\[main\]\\ninstallonly_limit=4/ $yumconf");
          if ($? == -1) {
            # give feedback, if system call produces an error
            my $errmsg = "command failed: $!";
            syslog(LOG_ERR, $errmsg);
            print STDERR $errmsg,"\n" if $verbose;
	  }
	}
    }
}
