#! perl

use strict;
use warnings;

use FindBin ();
use lib "$FindBin::Bin/../lib";

my $configfile = '/etc/apt-cacher/apt-cacher.conf';
my $verbose=1;

# Include the library for the config file parser
require('apt-cacher.pl');
# Read in the config file and set the necessary variables

# $cfg needs to be global for setup_ownership
our $cfg = eval{ read_config($configfile) };

# not sure what to do if we can't read the config file...
die "Could not read configuration file '$configfile': $@" if $@;

private_config();

# check whether we're actually meant to clean the cache
if ( $cfg->{clean_cache} ne 1 ) {
    printmsg("Maintenance disallowed by configuration item clean_cache\n");
    exit 0;
}

check_install(); # Before we give up rights

# change uid and gid if root and another user/group configured
if (($cfg->{user} && $cfg->{user} !~ 'root' && !$> )
    || ($cfg->{group} && $cfg->{group} !~ 'root' && !$) =~ /^0/)){
    printmsg("Invoked as root, changing to $cfg->{user}:$cfg->{group} and re-execing.\n");
    setup_ownership($cfg);
    # Rexec to ensure /proc/self/fd ownerships correct which are needed for red
    # patching with pdiffs
    exec($0, @ARGV) or die "Unable to rexec $0: $!\n";
}
# Output data as soon as we print it
local $| = 1;

load_checksum(); # Will disable checksum if BerkeleyDB not available

sub printmsg {
    my @args = @_;
    my $ret;
    $ret = print @args if $verbose;
    return $ret;
}

sub db_compact {
    my ($dbh) = @_; #db();
    printmsg "Waiting for CDS lock...\n";
    my $db_lock = $dbh->cds_lock();
    printmsg "Compacting checksum database....\n";
    my ($status, %results) = @{_db_compact($dbh)};
    if ($status) {
	printmsg "db_compact failed: $status\n";
    }
    else {
	printmsg " Compacted ". $results{compact_pages_free} ." pages\n Freed ". $results{compact_pages_truncated} ." pages\n";
    }
    return;
}

sub get_cursor {
    my ($dbh,$write)=@_;
    my $cursor = $dbh->db_cursor($write?BerkeleyDB->DB_WRITECURSOR:undef) or die $BerkeleyDB::Error;
    return $cursor;
}

if ($cfg->{checksum} and my $db=db()) {

    printmsg "Removing expired entries from checksum database\n";

    my $do_compact;
    {
	my $cursor = get_cursor($db,1);
	my ($filename,$data)=('','');
	while (cursor_next($cursor, \$filename, \$data) == 0)
	  {
	      $do_compact++;
	  }
    }
    printmsg "$do_compact\n";
    db_compact($db) if $do_compact;
}
