#!/usr/bin/perl

# ispCP ω (OMEGA) a Virtual Hosting Control Panel
# Copyright (C) 2001-2006 by moleSoftware GmbH - http://www.molesoftware.com
# Copyright (C) 2006-2010 by isp Control Panel - http://ispcp.net
#
#
# The contents of this file are subject to the Mozilla Public License
# Version 1.1 (the "License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
# License for the specific language governing rights and limitations
# under the License.
#
# The Original Code is "VHCS - Virtual Hosting Control System".
#
# The Initial Developer of the Original Code is moleSoftware GmbH.
# Portions created by Initial Developer are Copyright (C) 2001-2006
# by moleSoftware GmbH. All Rights Reserved.
# Portions created by the ispCP Team are Copyright (C) 2006-2010 by
# isp Control Panel. All Rights Reserved.
#
# The ispCP ω Home Page is:
#
#    http://isp-control.net
#


use FindBin;
use lib "$FindBin::Bin/";
require 'ispcp_common_code.pl';

use strict;

use warnings;

$main::htgroup_task_id = undef;

sub htgroup_mngr_start_up {

	my ($rs, $rdata) = (undef, undef);

	push_el(\@main::el, 'htgroup_mngr_start_up()', 'Starting...');

	# checking for master process;
	$rs = check_master();
	return $rs if ($rs != 0);

	# Let's clear Execution Logs, if any.

	if (-e $main::ispcp_htgroups_mngr_el) {

		$rs = del_file($main::ispcp_htgroups_mngr_el);

		return $rs if ($rs != 0);

	}

	#
	# getting task id and domain record id;
	#

	$main::htgroup_task_id = $ARGV[0];

	push_el(\@main::el, 'htgroup_mngr_start_up()', 'Ending...');

	return 0;

}

sub htgroup_mngr_shut_down {

	my $rs = undef;

	push_el(\@main::el, 'htgroup_mngr_shut_down()', 'Starting...');

	push_el(\@main::el, 'htgroup_mngr_shut_down()', 'Ending...');

	return 0;

}

#
# AuthGroupFile add/remove entries;
#

sub htgroup_add_group_line_data {

	push_el(\@main::el, 'htgroup_add_group_line_data()', 'Starting...');

	my ($line, $gname, $uname) = @_;

	if ($line !~ /( $uname$)|( $uname )/) {

		$line =~ s/$gname://;

		chomp($line);

		$line = "$gname:$line $uname\n";

	}

	push_el(\@main::el, 'htgroup_add_group_line_data()', 'Ending...');

	return $line;
}

sub htgroup_add_group_data {

	push_el(\@main::el, 'htgroup_add_group_data()', 'Starting...');

	my ($dmn_name, $gname, $uname) = @_;

	my $rs = undef;

	my $htgroups_file_name = $main::cfg{'HTACCESS_GROUPS_FILE_NAME'};

	my $apache_www_dir = $main::cfg{'APACHE_WWW_DIR'};

	my $htgroups_file = "$apache_www_dir/$dmn_name/$htgroups_file_name";

	my $htgroups_content = '';


	if (-e $htgroups_file) {

		my $gf_edit_flag = 0;

		open(F, '<', $htgroups_file);

		while (!eof(F)) {

			my $line = readline(F);

			if ($line !~ /^$gname:/) {

				$htgroups_content .= $line;

			} else {

				$htgroups_content .= htgroup_add_group_line_data($line, $gname, $uname);

				$gf_edit_flag++;

			}

		}

		$htgroups_content .= "$gname: $uname\n" if ($gf_edit_flag == 0);

		close(F);

	} else {

		$htgroups_content = "$gname: $uname\n";

	}

	if (-e "$apache_www_dir/$dmn_name/") {
		$rs = store_file($htgroups_file, $htgroups_content, $main::cfg{'ROOT_USER'}, $main::cfg{'ROOT_GROUP'}, 0644);
		return $rs if ($rs != 0);
	}

	push_el(\@main::el, 'htgroup_add_group_data()', 'Ending...');

	return 0;

}

sub htgroup_mngr_engine {

	my ($rs, $sql, $rows, $rdata) = (undef, undef, undef, undef);

	push_el(\@main::el, 'htgroup_mngr_engine()', 'Starting...');

	$sql = "
		SELECT
			`ugroup`,
			`members`,
			`status`,
			`id`,
			`domain_name`
		FROM
			`htaccess_groups` AS t1
		LEFT JOIN
			`domain` AS t2
		ON
			t1.`dmn_id` = t2.`domain_id`
		where
			t1.`dmn_id` = '".$main::htgroup_task_id."'
		and
			t1.`status` in ('toadd', 'change', 'delete', 'ok')
	";

	($rs, $rows) = doHashSQL($sql, 'id');
	return $rs if ($rs != 0);

	if (keys( %$rows ) != 0) {

		my $htgroups_file_name = $main::cfg{'HTACCESS_GROUPS_FILE_NAME'};

		my $apache_www_dir = $main::cfg{'APACHE_WWW_DIR'};

		my @ids = keys %$rows;

		my $htgroup_dmn  = @$rows{$ids[0]}->{'domain_name'};

		if (!defined $htgroup_dmn){

			$sql = "update `htaccess_groups` set `status`='orphaned' where `dmn_id` = '$main::htgroup_task_id'";
			($rs, $rdata) = doSQL($sql);
			return $rs if ($rs != 0);

			push_el(
				\@main::el, 'htgroup_mngr_engine()',
				"Detected orphan entry in table htaccess_groups, id: @$rows{$ids[0]}->{'id'} ".
				"Domain id $main::htgroup_task_id is missing!"
			);

			return -1;

		}

		my $htgroups_file = "$apache_www_dir/$htgroup_dmn/$htgroups_file_name";

		my $rs = open FH, ">$htgroups_file";

		return -1 if(!$rs);

		close FH;

		foreach (@ids) {

			my ($htgroup_name, $htgroup_members, $htgroup_status, $htgroup_id) =
				(@$rows{$_}->{'ugroup'}, @$rows{$_}->{'members'}, @$rows{$_}->{'status'}, @$rows{$_}->{'id'});

			push_el(\@main::el, 'htgroup_mngr_engine()', 'Working on '.$htgroup_name);

			push_el(\@main::el, 'htgroup_mngr_engine()', 'Working on id '.$_);

			if ($htgroup_status eq 'change' || $htgroup_status eq 'toadd' || $htgroup_status eq 'ok') {

				# only choice atm -> build the group again. Reset the old groupfile
				if ( defined($htgroup_members) && $htgroup_members ne '' ){

					foreach (split(',', $htgroup_members)) {

						my $id = $_;

						$sql = "select `uname` from `htaccess_users` where `id` = $id";

						($rs, $rdata) = doHashSQL($sql, 'uname');
						return $rs if ($rs != 0);

						my @unames = keys %$rdata;

						if(!@unames){

							push_el(\@main::el, 'htgroup_mngr_engine()', "ERROR htaccess_users with $id does not exits.");

							return -1;

						}

						my $uname  = @$rdata{$unames[0]}->{'uname'};

						$rs = htgroup_add_group_data($htgroup_dmn, $htgroup_name, $uname);

						return $rs if ($rs != 0);

					}

				}

				push_el(\@main::el, 'htgroup_mngr_engine()', 'Edit Group ID : '.$htgroup_id.'...');

				$sql = "update `htaccess_groups` set `status` = 'ok' where `id` = '$htgroup_id'";

			} elsif ($htgroup_status eq 'delete') {
				# since we build our file again and delete status is handled apart groups with status
				# 'delete' will get deleted...

				$sql = "delete from `htaccess_groups` where `id` = '$htgroup_id'";

				push_el(\@main::el, 'htgroup_mngr_engine()', 'Delete Group ID : '.$htgroup_id.'...');

			} else {

				push_el(\@main::el, 'htgroup_mngr_engine()', 'Failure modifying group in Domain $htgroup_dmn : $htgroup_name');

				$sql = "update `htaccess_groups` set `status`='failure' where `id` = '$htgroup_id'";

			}

			($rs, $rdata) = doSQL($sql);
			return $rs if ($rs != 0);

		}

		if ((not -e $htgroups_file) && (-e "$apache_www_dir/$htgroup_dmn/")) {

			my $rs = open FH, ">$htgroups_file";
			return -1 if(!$rs);

			close FH;

		}

	}

	push_el(\@main::el, 'htgroup_mngr_engine()', 'Ending...');

	0;

}

my $rs = undef;

$rs = htgroup_mngr_start_up();

if ($rs != 0) {

    dump_el(\@main::el, $main::ispcp_htgroups_mngr_el);

    htgroup_mngr_shut_down();

    exit 1;

}

$rs = htgroup_mngr_engine();

if ($rs != 0) {

    dump_el(\@main::el, $main::ispcp_htgroups_mngr_el);

    htgroup_mngr_shut_down();

    exit 1;

}

$rs = htgroup_mngr_shut_down();

if ($rs != 0) {

    dump_el(\@main::el, $main::ispcp_htgroups_mngr_el);

    exit 1;

}

exit 0;
