#!/usr/bin/perl
# #
# Software subject to following license(s):
#   Apache 2 License (http://www.opensource.org/licenses/apache2.0)
#   Copyright (c) Responsible Organization
#

# #
# Current developer(s):
#   Luis Fernando Muñoz Mejías <Luis.Munoz@UGent.be>
#

# 
# #
# ccm, 26.2.0, 1, Tue Apr 07 2026
#
#
# Initialise local config cache
#

package ccm_initialise;

use strict;
use warnings;

BEGIN {
    unshift(@INC, '/usr/lib/perl');
    pop @INC if $INC[-1] eq '.';
}

use CAF::Application;
use CAF::Reporter 16.8.1;
use LC::Exception qw(SUCCESS throw_error);
our @ISA = qw(CAF::Application CAF::Reporter CAF::Path);

# needed for method overriding
no warnings 'redefine';

#
# application specific options:
#
sub app_options {

    # local lexicals
    my @options;

    # build options
    push (@options,

          { NAME    => 'cfgfile=s',
            HELP    => 'configuration file for ccm-initialise' },

          { NAME    => 'logfile=s',
            HELP    => 'path/filename to use for ccm-initialise logs',
            DEFAULT => '/var/log/ccm-initialise.log' },

          { NAME    => 'debug|d=i',
            DEFAULT => '0',
            HELP    => 'Turn on debugging messages' });

    return \@options;
}

#
# initialise
#
sub _initialize {

    # local lexicals
    my $self = shift;

    # version and usage
    $self->{'VERSION'} = "26.2.0";
    $self->{'USAGE'}   = sprintf("Usage: %s [OPTIONS...]", $0);

    $self->{LOG_APPEND} = 1;
    $self->{LOG_TSTAMP} = 1;

    # initialise
    unless ($self->SUPER::_initialize(@_)) {
        return;
    }

    $self->set_report_logfile($self->{'LOG'});
    # Enable verbose_logfile
    $self->setup_reporter(undef, undef, undef, undef, 1);

    return SUCCESS;
}


#-- Main ---------------------------------------------------------------------------------------------#

package main;

use strict;
use warnings;

use Getopt::Long;
use File::Path;
use EDG::WP4::CCM::CCfg qw(initCfg getCfgValue);
use EDG::WP4::CCM::Fetch::ProfileCache qw(GetPermissions SetMask MakeCacheRoot);

$ENV{PATH} = join(":", qw(/bin /usr/bin /sbin /usr/sbin));

our ($this_app);

# unbuffer STDOUT & STDERR
autoflush STDOUT 1;
autoflush STDERR 1;

# initialise main class
unless ($this_app = ccm_initialise->new($0, @ARGV)) {
    throw_error("Cannot start application");
    exit (1);
}

$this_app->verbose("ccm-initialise begin");

# Options
initCfg($this_app->option("cfgfile"));

my ($dopts, $fopts, $mask) = GetPermissions($this_app, getCfgValue('group_readable'), getCfgValue('world_readable'));
# Set logfile permissions
$this_app->status($this_app->option('logfile'), %$fopts);

my $cache_root = getCfgValue('cache_root');

# remove any existing cache
$this_app->verbose("Removing cache_root $cache_root");
rmtree($cache_root, 0, 0);

# Use Warn for both info and error
$this_app->verbose("Creating cache_root $cache_root and subdirectories");

# Change the whole cacheroot and profile dir to allow correct permissions
SetMask($this_app, $mask, $dopts->{group});
MakeCacheRoot($this_app, $cache_root, $dopts);

# make global lock file (mask and GID take care of the permissions)
$this_app->verbose("Creating lockfile");
open (my $TMP, '>', "$cache_root/global.lock");
print $TMP "no\n";
close $TMP;

$this_app->verbose("ccm-initialise complete");
exit(0);

__END__

=head1 NAME

ccm-initialise - initialise local config cache

=head1 DESCRIPTION

Create an initial directory hierarchy for the local config cache, along
with the necessary lock files.

=head1 SYNOPSIS

ccm-initialise [I<OPTIONS>]

=head1 OPTIONS

=over 4

=item B<-d>, B<--debug>

Turn on debugging messages.

=item B<--cfgfile>=I<file>

The I<file> is the WP4 local cache configuration file, also used by the
B<fetch> program; cache-initialise uses it to establish the location of
the cache root directory.  If no I<file> is specified, the default path
is /etc/ccm.conf.  If the file is missing or specifies no value
for the cache root, that defaults to /var/lib/ccm.

=back

=cut
