#!/usr/bin/perl
###############################################################################
#    Copyright (C) 2002-2204 by Eric Gerbier
#    Bug reports to: gerbier@users.sourceforge.net
#    $Id: test_os.sh 872 2006-08-17 09:32:26Z gerbier $
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
###############################################################################
# this script is to be called at end of install
# it is in perl to allow it to work on windows

use strict;
use warnings;

use Getopt::Long;      # option analysis
use File::Basename;    # dirname
use File::Spec;        # rel2abs
use English qw(-no_match_vars);

## no critic (ProhibitPackageVars)
use vars qw( $Verbose );
## use critic
my $Version = '0.4-0';

#############################################################
# just display program version
sub version($) {
	my $version = shift @_;
	print "\n";
	print
"afick_postinstall : another file integrity checker configurator\nversion $version\n";
	return;
}
#############################################################
# usage
# print some help
sub usage($) {
	my $version = shift @_;
	print <<"EOHELP";

Usage: $0 [options]

afick_postinstall options (control afickonfig)  : 
 -c|--config_file file        configname of config file to use
 -h|--help                    show this help page
 -V|--version                 show afickonfig version
 -v|--verbose		     for debugging


Disclaimer:
This script is intended to provide a means for
detecting changes made to files, via a regular
comparison of MD5 hashes to an established baseline. 

Copyright (c) 2006 Eric Gerbier <gerbier\@users.sourceforge.net>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
EOHELP
	return;
}
#############################################################

# afick library
# it is used on post-install, so all should be ok
my $dirname = File::Spec->rel2abs( dirname($PROGRAM_NAME) );
require $dirname . '/afick-common.pl';

$OUTPUT_AUTOFLUSH = 1;

# arg line
my $help;
my $configfile;
my $version;
Getopt::Long::Configure('no_ignore_case');
if (
	!GetOptions(
		'config_file|c=s' => \$configfile,
		'help|h'          => \$help,
		'verbose|v'       => \$Verbose
	)
  )
{
	usage($Version);
	die "abort : incorrect option\n";

}
if ($help) {

	# -h : help
	usage($Version);
	exit;
}
elsif ($version) {

	# -V : version
	version($Version);
	exit;
}

if ( !$configfile ) {
	$configfile = get_default_config();
}
debug("configuration file is $configfile");

# first : create empty history file if a new install (not an upgrade)
# to avoid clean_config to remove directive

# get history file name from configuration file
my %macros;
my %alias = get_default_alias();
my %directive;
my %rules;
my %onlydir;

get_configuration( $configfile, \%macros, \%alias, \%directive, \%rules,
	\%onlydir );
my $history = $directive{'history'};

# create it if necessary
touch($history) if ($history);

# second : append local config file to config file if it exists
# to avoid duplicate copying, we read first until the mark then write
# (just append at end may append many times the same lines)
# be carefull : this is also defined in afick_preinstall !
my $mark         = 'put your local config below';
my $local_config = $configfile . '.local';

# read current config to mark and store
debug('modify configuration file');
## no critic (RequireBriefOpen)
my $fh_config;
if ( !open $fh_config, '<', $configfile ) {
	die "can not read $configfile : $ERRNO\n";
}
my @config;
while (<$fh_config>) {

	#search for environment variable : ${} and replace it
	if (m/(.*)\${(\w+)}(.*)/) {
		$_ = $1 . $ENV{$2} . $3 . "\n";
		debug("replace env var $2");
	}
	push @config, $_;
	last if (m/$mark/);
}
close $fh_config or warning("can not close $configfile : $ERRNO");

debug('rewrite config');

# rewrite it
if ( !open $fh_config, '>', $configfile ) {
	die "can not write to $configfile : $ERRNO\n";
}
foreach my $line (@config) {
	print {$fh_config} $line;
}

# add local config
debug('add local config');
if ( -s $local_config ) {
	my $fh_local;
	if ( open $fh_local, '<', $local_config ) {

		while (<$fh_local>) {
			print {$fh_config} $_;
			debug("copy line $_");
		}
		close $fh_local or warning("can not close $local_config : $ERRNO");
	}
	else {
		warning("can not open $local_config : $ERRNO");
	}
	close $fh_config or warning("can not close $configfile : $ERRNO");

	# remove local config
	unlink $local_config;
}

# third : clean configuration
debug('clean configuration');
debug("path = $dirname");
system $dirname . '/afickonfig.pl', '-c', $configfile, '--clean_config';
system $dirname . '/afickonfig.pl', '-c', $configfile, '--addpath', '--addlib';
