#!/usr/bin/perl -w
# This script (sophomorix-ui) is maintained by Rüdiger Beck
# It is Free Software (License GPLv3)
# If you find errors, contact the author
# jeffbeck@web.de  or  jeffbeck@linuxmuster.net

# modules
use strict;
use Getopt::Long;
Getopt::Long::Configure ("bundling");
use Sophomorix::SophomorixConfig;
use List::MoreUtils qw(uniq);
use Data::Dumper;
$Data::Dumper::Indent = 1;
$Data::Dumper::Sortkeys = 1;
$Data::Dumper::Useqq = 1;
$Data::Dumper::Terse = 1; 
use Net::LDAP;
use JSON;
use Sophomorix::SophomorixBase qw(
                                 print_line
                                 print_title
                                 unlock_sophomorix
                                 lock_sophomorix
                                 log_script_start
                                 log_script_end
                                 log_script_exit
                                 backup_auk_file
                                 get_passwd_charlist
                                 get_plain_password
                                 check_options
                                 config_sophomorix_read
                                 result_sophomorix_init
                                 result_sophomorix_add
                                 result_sophomorix_add_summary
                                 result_sophomorix_check_exit
                                 result_sophomorix_print
                                 console_print_quota_user
                                 console_print_mailquota_user
                                 remove_from_list    
                                 json_dump
                                 );
use Sophomorix::SophomorixSambaAD qw(
                                 AD_school_create
                                 AD_bind_admin
                                 AD_dns_get
                                 AD_get_user
                                 AD_get_AD_for_check
                                 AD_check_ui
                                 AD_user_kill
                                 AD_unbind_admin
                                 AD_object_search
                                 AD_user_create
                                 AD_user_update
                                 AD_user_setquota
                                 AD_group_create
                                 AD_group_kill
                                 AD_group_addmember
                                 AD_get_schoolname
                                 AD_get_name_tokened
                                 AD_group_update
                                 AD_project_sync_members
                                 AD_dn_fetch_multivalue
                                 AD_get_passwd
                                    );
my @arguments = @ARGV;

# option vars
$Conf::log_level=1;
my $help=0;
my $info=0;
my $json=0;
my $school="";
my $force=0;
my $user="";

$Conf::log_level=1;

# Parsen der Optionen
my $testopt=GetOptions(
           "help|h" => \$help,
           "info|i" => \$info,
           "json|j+" => \$json,
           "verbose|v+" => \$Conf::log_level,
           "school=s" => \$school,
           "force|f" => \$force,
          );

my %sophomorix_result=&result_sophomorix_init("sophomorix-ui");
# Prüfen, ob Optionen erkannt wurden
&check_options($testopt,\%sophomorix_result,$json);

# Reading Configuration
my ($ldap,$root_dse) = &AD_bind_admin(\@arguments,\%sophomorix_result,$json);
my $root_dns=&AD_dns_get($root_dse);
my %sophomorix_config=&config_sophomorix_read($ldap,$root_dse,\%sophomorix_result);
my ($smb_admin_pass)=&AD_get_passwd($DevelConf::sophomorix_file_admin,
                                     $DevelConf::secret_file_sophomorix_file_admin);


# --help
if ($help==1) {
   # Scriptname ermitteln
   my @list = split(/\//,$0);
   my $scriptname = pop @list;
   # Befehlbeschreibung
   print('
sophomorix-ui sets the AD Attributes for user interfaces.

Options
  -h  / --help
  -v  / --verbose
  -vv / --verbose --verbose

Update what has changed:
  sophomorix-ui

Update every user:
  sophomorix-ui --force

Show what would be changed:
  sophomorix-ui -i
  sophomorix-ui -ij

Limit changes to one school:
  --school <school>

Please see the sophomorix-ui(8) man pages for full documentation
');
   print "\n";
   exit;
}

&result_sophomorix_check_exit(\%sophomorix_result,\%sophomorix_config,$json);


# create schoollist from options
# --school <school>
my @schoollist=();
if ($school ne ""){
    if (exists $sophomorix_config{'SCHOOLS'}{$school}){
	push @schoollist,$school;
    } else {
        print "\nERROR: $school is not a school!\n\n";
	exit 88;
    }
} else {
    # without option use all schools
    @schoollist=@{ $sophomorix_config{'LISTS'}{'SCHOOLS'} };
}


# get user data from AD
my ($ref_AD_check) = &AD_get_AD_for_check({ldap=>$ldap,
                                           root_dse=>$root_dse,
                                           root_dns=>$root_dns,
                                           admins=>"TRUE",
                                           sophomorix_config=>\%sophomorix_config,
                                         });

# verify user data against old values
my $ref_AD_check_ui=&AD_check_ui({ldap=>$ldap,
                                  root_dse=>$root_dse,
                                  root_dns=>$root_dns,
                                  force=>$force,
                                  ref_AD_check=>$ref_AD_check,
                                  sophomorix_config=>\%sophomorix_config,
                                 });
#print Dumper($ref_AD_check_ui);
if ($info==1){
    &json_dump({json => $json,
                jsoninfo => "UI",
                jsoncomment => "sophomorix ui",
                object_name => $school,
                log_level => $Conf::log_level,
                hash_ref=>$ref_AD_check_ui,
                sophomorix_config=>\%sophomorix_config,
              });
    exit;
}



# ===========================================================================
# Start
# ===========================================================================
&log_script_start(\@arguments,\%sophomorix_result,\%sophomorix_config);

my $max_user_count=0;
my $user_count=0;
my $user_count_total=0;

my @rolelist=("globaladministrator","schooladministrator","teacher","student","parent","staff");


if ($school eq ""){
    # walk through all users
    foreach my $role (@rolelist){
        $user_count=0;
        $max_user_count=$#{ $ref_AD_check_ui->{'LISTS_UPDATE'}{'USERS_by_sophomorixRole'}{$role} }+1;
        foreach my $user (@{ $ref_AD_check_ui->{'LISTS_UPDATE'}{'USERS_by_sophomorixRole'}{$role} }){
            $user_count++;
            $user_count_total++;
            &AD_user_update({ldap=>$ldap,
                             root_dse=>$root_dse,
                             dn=>$ref_AD_check_ui->{'UI'}{'USERS'}{$user}{'dn'},
                             user=>$user,
                             webui_permissions_calculated=>$ref_AD_check_ui->{'UI'}{'USERS'}{$user}{'CALCLIST'},
                             user_count=>$user_count,
                             max_user_count=>$max_user_count,
                             json=>$json,
                             sophomorix_config=>\%sophomorix_config,
                             sophomorix_result=>\%sophomorix_result,
                           });
        }
    }
} else {
    # walk through all schools, count by school
    foreach my $school (@schoollist){
        &Sophomorix::SophomorixBase::print_title("Setting sophomorixWebuiPermissionsCalculated in $school");
        if ( exists $ref_AD_check_ui->{'LISTS_UPDATE'}{'USER_by_sophomorixSchoolname'}{$school} ){
	    $max_user_count=$#{ $ref_AD_check_ui->{'LISTS_UPDATE'}{'USER_by_sophomorixSchoolname'}{$school} }+1;
            }
        if ($max_user_count==0){
            print "\n0 SophomorixWebuiPermissionsCalculated updates in school $school\n\n";
            next;
        }
        foreach my $role (@rolelist){
            &Sophomorix::SophomorixBase::print_title("   * sophomorixRole: $role");
            foreach my $user (@{ $ref_AD_check_ui->{'LISTS_UPDATE'}{'USER_by_sophomorixSchoolname_by_sophomorixRole'}{$school}{$role} }){
                $user_count++;
                $user_count_total++;
                &AD_user_update({ldap=>$ldap,
                                 root_dse=>$root_dse,
                                 dn=>$ref_AD_check_ui->{'UI'}{'USERS'}{$user}{'dn'},
                                 user=>$user,
                                 webui_permissions_calculated=>$ref_AD_check_ui->{'UI'}{'USERS'}{$user}{'CALCLIST'},
                                 user_count=>$user_count,
                                 max_user_count=>$max_user_count,
                                 json=>$json,
                                 sophomorix_config=>\%sophomorix_config,
                                 sophomorix_result=>\%sophomorix_result,
                              });
            }
        }
    }
}



&result_sophomorix_add_summary({
                     NAME=>"UPDATED UI", 
                     RESULT=>$user_count_total, 
                     RESULT_TYPE => "integer",
                     DESCRIPTION_POST => "user ui updated", 
                     DESCRIPTION_PRE => " user ui updated", 
                     FORMAT_TYPE => 1,
                     sophomorix_result=>\%sophomorix_result,
 		               });



&AD_unbind_admin($ldap);
&log_script_end(\@arguments,\%sophomorix_result,\%sophomorix_config,$json);
############################################################
# End
############################################################



############################################################
# subs
############################################################
