#!/usr/bin/perl -w

my $audit_toggle_file = '/etc/libcreds_audit';
my $libcreds_saved_name = '/usr/lib/libcreds-saved';

my $libcreds;
while (</usr/lib/libcreds.so.*>)
{
    next if (readlink $_);
    die "Multiple libcreds version: $_\n" if (defined $libcreds);
    $libcreds = $_;
}
#warn "The current libcreds library: $libcreds\n";

my $libcreds_audit;
while (</usr/lib/libcreds-audit.so.*>)
{
    next if (readlink $_);
    die "Multiple libcreds-audiot version: $_\n" if (defined $libcreds_audit);
    $libcreds_audit = $_;
}
#warn "The current libcreds-audit library: $libcreds_audit\n";

my $libcreds_saved;
$libcreds_saved = $libcreds_saved_name
    if (-e $libcreds_saved_name);

die "libcreds not installed\n" unless (defined $libcreds);

my $audit_fh;

my $audit_on;
while (@ARGV)
{
    my $cmd = shift;

    die "Extra command line argument '$cmd'\n"
	if (defined $audit_on);

    if ($cmd eq 'on')
    {
	die "Cannot turn audit on -- libcreds2-audit package not installed\n"
	    unless (defined $libcreds_audit);
	$audit_on = 1; 
    }
    elsif ($cmd eq 'off')
    {
	$audit_on = 0;
    }
    else
    {
	die "Unimplemented command '$cmd': use either 'on', 'off' or nothing\n";
    }
}
if (!defined $audit_on)
{
    # libcreds_audit without 'on' or 'off'

    if (open($audit_fh, "<$audit_toggle_file"))
    {
	# Audit toggle file exists, turn on or off based on
	# it's content.
	my $flag = <$audit_fh>;
	$audit_on = ($flag =~ /^on$/);
	close($audit_fh);
    }
    else
    {
	# If this script is called without explicit 'on' or 'off',
	# and if /etc/libcreds_audit does not exist, then create
	# it and set audit_on by default.
	$audit_on = 1;
    }
}

if ($audit_on != (defined $libcreds_saved))
{
    # Audit configuration needs to be changed

    if ($audit_on)
    {
	# Turn audit version on
	$libcreds_saved = $libcreds_saved_name;
	die "Cannot rename '$libcreds' to '$libcreds_saved'\n"
	    unless (rename($libcreds,$libcreds_saved));
	die "Cannot link '$libcreds' to '$libcreds_audit' -- system is in broken state\n"
	    unless (link($libcreds_audit, $libcreds));
    }
    else
    {
	# Turn audit version off
	die "Cannot rename '$libcreds_saved' to '$libcreds'\n"
	    unless (rename($libcreds_saved, $libcreds));
	undef $libcreds_saved;
    }

    # Record the current state in 
    if (open($audit_fh, ">$audit_toggle_file"))
    {
	print $audit_fh $audit_on ? 'on' : 'off';
	close ($audit_fh);
    }
    else
    {
	warn "Oops! Cannot record the new state into '$audit_toggle_file'\n";
    }
}


if (defined $libcreds_saved)
{
    warn "Audit configuration\n";
}
else
{
    warn "Standard configuration\n";
}
