#!/usr/bin/perl
#
# Automated Userinfo update script
#
# Copyright Michigan State University Board of Trustees
#
# 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/
#
    use strict;
    use lib '/home/httpd/lib/perl';
    use localenroll;
    use LONCAPA::Configuration;
    use LONCAPA::Enrollment;
    use Apache::lonnet;
    use Apache::loncommon;

    my @info = ('inststatus','lockedname','lastname','firstname','id');
    # find out which users we need to examine
    my @domains = sort(&Apache::lonnet::current_machine_domains());
    foreach my $dom (@domains) {
        my %domconfig = &Apache::lonnet::get_dom('configuration',['autoupdate'],
                                                 $dom);
        #only run if configured to
        my $run_update = 0;
        my $settings;
        if (ref($domconfig{'autoupdate'}) eq 'HASH') {
            $settings = $domconfig{'autoupdate'};
            if ($settings->{'run'} eq 'yes') {
                $run_update = 1;
            }
        }
        next if (!$run_update);
        my %users;
        my @types = ('active','future');
        my @roles = ('st');
        my @cdoms = ($dom);
        my $dir = $Apache::lonnet::perlvar{lonUsersDir}.'/'.$dom;
        &descend_tree($dir,0,\%users);
        foreach my $uname (keys(%users)) {
            my %userhash = &Apache::lonnet::userenvironment($dom,$uname,@info);
            if (!$userhash{'lockedname'} && !$userhash{'internalname'}) {
                my %userinfo = &localenroll::get_userinfo($dom,$uname,%userhash);
                if (keys(%userinfo) > 0) {
                    my @fields = @{$settings->{'default'}};
                    if ($userhash{'inststatus'} ne '') {
                        if (ref($settings->{$userhash{'inststatus'}}) eq 'ARRAY') {
                            @fields = @{$settings->{$userhash{'inststatus'}}};
                        }
                    }
                    my %changes;
                    my $changed;
                    foreach my $field (@fields) { 
                        if ($userhash{$field} ne $userinfo{$field}) {
                            $changed = 1;
                            if ($settings->{'classlists'} eq 'yes') { 
                                if ($field eq 'id') {
                                    $changes{'id'} = 1;
                                } elsif ($field eq 'lastname' || $field eq 'firstname' || $field eq 'middlename' || $field eq 'gen') {
                                    $changes{'fullname'} = 1;
                                }
                            }
                        }  
                    }
                    # Make the change
                    if ($changed) {
                        my %userupdate;
                        foreach my $field (@fields) {
                            $userupdate{$field} = $userinfo{$field};
                        }
                        my $putresult = &Apache::lonnet::put
                                       ('environment',\%userupdate,$dom,$uname);
                        if ($putresult eq 'ok') {
                            if ($settings->{'classlists'} eq 'yes') {
                                if ($changes{'id'} || $changes{'fullname'}) {
                                    my %roleshash = 
                                        &Apache::lonnet::get_my_roles($uname,
                                                  $dom,\@types,\@roles,\@cdoms);
                                    foreach my $item (%roleshash) {
                                        my ($cnum,$cdom,$role) = split(/:/,$item);
                                        my ($start,$end) = split(/:/,$roleshash{$item});
                                        if (&Apache::loncommon::is_course($cdom,$cnum)) {
                                            my $result = &update_classlist($cdom,$cnum,$dom,$uname,\%userupdate);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }


sub descend_tree {
    my ($dir,$depth,$alldomusers) = @_;
    if (-d $dir) {
        opendir(DIR,$dir);
        my @contents = grep(!/^\./,readdir(DIR));
        closedir(DIR);
        $depth ++;
        foreach my $item (@contents) {
            if ($depth < 4) {
                &descend_tree($dir.'/'.$item,$depth,$alldomusers);
            } else {
                if (-e $dir.'/'.$item.'/environment.db') {
                    
                    $$alldomusers{$item} = '';
                }
            }
        }
    }
}

sub update_classlist {
    my ($cdom,$cnum,$udom,$uname,$user) = @_;
    my ($uid,$fullname,$classlistentry);
    my $fullname = 
        &Apache::lonnet::format_name($user->{'first'},$user->{'middle'},
                                     $user->{'last'},$user->{'gene'},'lastname');
    my %classhash = &Apache::lonnet::get('classlist',[$uname.':'.$udom],
                                         $cdom,$cnum);
    my @classinfo = split(/:/,$classhash{$uname.':'.$udom});
    my $ididx=&Apache::loncoursedata::CL_ID() - 2;
    my $nameidx=&Apache::loncoursedata::CL_FULLNAME() - 2;
    for (my $i=0; $i<@classinfo; $i++) {
        if ($i == $ididx) {
            if (defined($user->{'id'})) {
                $classlistentry .= $user->{'id'}.':';
            } else {
                $classlistentry .= $classinfo[$i].':';
            }
        } elsif ($i == $nameidx) {
            $classlistentry .= $fullname.':';
        } else {
            $classlistentry .= $classinfo[$i].':';
        }
    }
    $classlistentry =~ s/:$//;
    my $reply=&Apache::lonnet::cput('classlist',
                                    {"$uname:$udom" => $classlistentry},
                                    $cdom,$cnum);
    if (($reply eq 'ok') || ($reply eq 'delayed')) {
        return 'ok';
    } else { 
        return 'error: '.$reply;
    }
}

