#!/usr/bin/perl

=pod

=head1 NAME

add_domain_coordinator_privilege.pl - Add domain coordinator to an
exisiting user on a LON-CAPA system.

=cut

# The LearningOnline Network
#
# add_domain_coordinator_privilege.pl - Add domain coordinator to an
#    exisiting user on a LON-CAPA system.
#
# $Id: add_domain_coordinator_privilege.pl,v 1.7 2011/05/29 17:54:21 raeburn Exp $
#
# This file is part of the LearningOnline Network with CAPA (LON-CAPA).
#
# LON-CAPA 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.
#
# LON-CAPA 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.
#
# You should have received a copy of the GNU General Public License
# along with LON-CAPA; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# /home/httpd/html/adm/gpl.txt
#
# http://www.lon-capa.org/
#
###

=pod

=head1 DESCRIPTION

Automates the steps for domain coordinator creation.  This
program also describes a manual procedure (see below).

These are the steps that are executed on the linux operating system:

=over 4

=item * 

Tests to see if user already exists for LON-CAPA, if not it aborts. 

=item *

Set roles.hist and roles.db

=back

=cut

# NOTE: I am interspersing the manual procedure with the automation.
# To see the manual procedure, do perldoc ./make_domain_coordinator.pl

# This is a standalone script.  It *could* alternatively use the
# lcuseradd script, however lcuseradd relies on certain system
# dependencies.  In order to have a focused performance, I am trying
# to avoid system dependencies until the LON-CAPA code base becomes
# more robust and well-boundaried.  make_domain_coordinator.pl should be able
# to run freely as possible, irrespective of the status of a LON-CAPA
# installation.

# ---------------------------------------------------- Configure general values

use lib '/home/httpd/lib/perl/';
use LONCAPA;
use Apache::lonnet;
use Apache::loncommon;
use Apache::lonlocal;

=pod

=head1 OPTIONS

There are no flags to this script.

usage: add_domain_coordinator_privilege.pl [USERNAME:DOMAIN] [NEWDOMAIN]

The first argument specifies the user name domain of an existing user.

The second argument specifies the domain to add to coordinate.

=cut

my ($user,$add_domain)=(@ARGV);
my $lang = &Apache::lonlocal::choose_language();
&Apache::lonlocal::get_language_handle(undef,$lang);

if ($< != 0) { # Am I root?
   print(&mt('You must be root in order to assign domain coordinator roles.').
         "\n");
}

# ----------------------------------------------- So, are we invoked correctly?
# Two arguments or abort
if (@ARGV!=2) {
    print(&mt('usage: [_1]','add_domain_coordinator_privilege.pl [USERNAME:DOMAIN] [NEWDOMAIN]').
	"\n");
    exit;
}
my ($username,$domain)=split(':',$user);
if (!grep(/^\Q$add_domain\E$/,&Apache::lonnet::current_machine_domains())) {
    print(&mt('**** ERROR **** Domain [_1] is unknown.',$add_domain)."\n");
    exit;
}

my $udpath=&propath($domain,$username);
if (!-d $udpath) {
    print(&mt('**** ERROR **** [_1] is NOT already defined as a LON-CAPA '.
	 'user.',$user)."\n");
    exit;
}

=pod

=head1 MANUAL PROCEDURE

There are 2 steps to manually recreating what this script performs
automatically.

You need to decide on two pieces of information
to create a domain coordinator.

 * USERNAME (kermit, albert, joe, etc)
 * DOMAIN (should be a domain for thsi machine from domain.tab)

The examples in these instructions will be based
on two example pieces of information:

 * USERNAME=dc103
 * DOMAIN=103

You will also need to know your "root" password
or your "www" password.

=over 4

=pod

=item 1. (as www). Run CVS:loncapa/doc/rolesmanip.pl:

 Command: [prompt %] perl rolesmanip.pl NEWDOMAIN USERNAME
 Example: [prompt %] perl rolesmanip.pl 103 dc103

=cut

use GDBM_File; # A simple key-value pairing database.

my $rolesref=&LONCAPA::locking_hash_tie("$udpath/roles.db",&GDBM_WRCREAT());
if (!$rolesref) {
    print(&mt('unable to tie [_1]',"roles db: $udpath/roles.db")."\n");
    exit;
}
my $status;
my $now = time;
if (exists($rolesref->{'/'.$add_domain.'/_dc'})) {
    my ($role,$end,$start) = split('_',$rolesref->{'/'.$add_domain.'/_dc'});
    print(&mt("[_1] already has a dc privilege for [_2].",
	      $user,$add_domain)."\n");
    if ($start) {
	print(&mt("Start date: [_1]",&Apache::lonlocal::locallocaltime($start)).
	      "\n");
	if (!$end) {
	    print(&mt("No planned end date.")."\n");
	} else {
            print(&mt("End date: [_1]",&Apache::lonlocal::locallocaltime($end)).
                  "\n");
        }
	if (($start <= $now) && (!$end || $end > $now)) {
	    print(&mt("It is currently active.")."\n");
	    $status = 'active';
	}
    } elsif ($end) {
	print(&mt("End date: [_1]",&Apache::lonlocal::locallocaltime($end)).
	      "\n");
	if ($end > $now) {
	    print(&mt("It is currently active.")."\n");
	    $status = 'active';
	}
    }
    if ((!$start) && (!$end)) {
	print(&mt("It is currently active.")."\n");
	$status = 'active';
    }
    unless ($status eq 'active') {
        print(&mt("It is currently not active. Proceeding to make role active now.")."\n");
    }
}

if ($status eq 'active') {
    &LONCAPA::locking_hash_untie($rolesref);
    exit(0);
}

my $now = time;
$rolesref->{'/'.$add_domain.'/_dc'}='dc_0_'.$now; # Set the domain coordinator role.
open(OUT, ">$udpath/roles.hist"); # roles.hist is the synchronous plain text.
foreach my $key (keys(%{$rolesref})) {
    print(OUT $key.' : '.$rolesref->{$key}."\n");
}
close(OUT);
&LONCAPA::locking_hash_untie($rolesref);


`chown www:www $udpath/roles.hist`; # Must be writeable by httpd process.
`chown www:www $udpath/roles.db`; # Must be writeable by httpd process.

my %perlvar = %{&LONCAPA::Configuration::read_conf('loncapa.conf')};
my $dompath = $perlvar{'lonUsersDir'}.'/'.$domain;
my $domrolesref = &LONCAPA::locking_hash_tie("$dompath/nohist_domainroles.db",&GDBM_WRCREAT());

if (!$domrolesref) {
    print(&mt('unable to tie [_1]',"nohist_domainroles db: $dompath/nohist_domainroles.db")."\n");
    exit;
}

# Store in nohist_domainroles.db
my $domkey=&LONCAPA::escape('dc:'.$username.':'.$domain.'::'.$domain.':');
$domrolesref->{$domkey}= &LONCAPA::escape('0:'.$now);
&LONCAPA::locking_hash_untie($domrolesref);

system('/bin/chown',"www:www","$dompath/nohist_domainroles.db"); # Must be writeable by httpd process.
system('/bin/chown',"www:www","$dompath/nohist_domainroles.db.lock");

=pod

=item 2.

You may further define the domain coordinator user (i.e. dc103)
by going to http://MACHINENAME/adm/createuser.

=cut

# Output success message, and inform sysadmin about how to further proceed.
print(&mt('[_1] is now a domain coordinator for [_2].',$username,$add_domain).
      "\n");
exit;

