#!/usr/bin/perl

########## Confixx(R) 3.0 Professional ############
####### Copyright SWsoft, Inc. 2004-2005 ##########
#### http://www.sw-soft.com - info@sw-soft.com ####

# Requires:
# * path to subs/ dir included
# * path to install/ dir included

use DBI;
use DBD::mysql;
##use DBD::Pg;## mysql only !!!

use lib_module_db;
use lib_module_common;

&initConfig;

my @files = (
	'cronjobs.pl',
	'custom_skins.pl'
);

$dbh = DBI->connect($db_address, $dbUser, $dbPw)
        or die( &ltext('db_connect', '#XXX', $DBI::errstr) );
	
foreach my $inc_file (@files) {
	safe_do "$installDir/install/$inc_file";
}

sub install_confixx_300 {
	my @routines = (
		'register_predefined_skins_300'
	);
	foreach my $routine (@routines) {
		&$routine;
	}
}

sub upgrade_confixx_300 {
	my @routines = (
		'register_predefined_skins_300',
		'upgrade_skins_300',
		'add_apache_to_users_300',
		'update_cronjobs_300',
	);
	foreach my $routine (@routines) {
		&$routine;
	}
}

#
# Common subroutines
#

sub inst_description {
	print "@_\n";
}

sub inst_finish_ok {
	print "..finished\n";
}

sub inst_finish_skipped($) {
    my ($msg) = @_;
    print "..skipped\n\t$msg\n"; 
}

sub inst_finish_failed($) {
    my ($msg) = @_;
    print "..failed\n\t$msg\n"; 
}

sub inst_db_connection {
	return $dbh;
}

sub group_mem() {
	my ($gr_name, @members) = @_;
	
	use File::Basename;
	my ($group_file, $group_dir) = &fileparse($groupDir);
	
	use File::Temp qw(tempfile);
	my ($temp_fh, $temp_name) = &tempfile("${group_file}XXXXXX", DIR => $group_dir);
	unless ($temp_fh || $temp_name) {
		die("Can not create temp file '$temp_name' in $group_dir: $!\n");
	}
	
	print "temp name: $temp_name\n";
	open(GROUP, "<$groupDir")
		or die("Can not open $groupDir: $!\n");
	while(<GROUP>){
		chomp;
		my $str = $_;
		unless ($str =~ /^(.*):(.*):(\d+)(:(.*))?$/) {
		    print $temp_fh "$str\n";
		    next;
		}
		print "$str\n";
		my ($name, $passwd, $gid, $members) = ($1, $2, $3, $5);
		if ($name eq $gr_name) {
			my $mem_str = join ',', @members;
			print $temp_fh "$name:$passwd:$gid:$mem_str\n";
		} else {
		    print $temp_fh "$str\n";
		}

	}
	close($temp_fh) 
		or die("Can not save file '$temp_file': $!\n"); 
	close(GROUP)
		or die("Can not save file '$groupDir': $!\n"); 

	use File::Copy;
	if (-e "$groupDir.sav") {
		unlink "$groupDir.sav" 
			or die("Can not remove '$groupDir.sav' file: $!\n")
	}
	&copy($groupDir, "$groupDir.sav")
		or die("Can not save '$groupDir' to '$groupDir.sav': $!\n");
	&move($temp_name, $groupDir) 
		or die("Can not set new $groupDir: $!\n");
	chmod(0644,$groupDir);	
	return 1;
}

# / common subroutines

END {
	$dbh->disconnect;
}

1;
