#
# Copyright (c) 2001 SuSE GmbH Nuernberg, Germany.  All rights reserved.
# Copyright (c) 2002 SuSE Linux AG Nuernberg, Germany.  All rights reserved.
# Copyright (c) 2005 Peter Varkoly Fuerth, Germany.  All rights reserved.
#
#
# $Id: profil.pm,v 1.12 2006/12/07 18:14:19 pv Exp $
#
package profil;
use strict;
use CGI qw(-no_xhtml);
use CGI::Carp qw(fatalsToBrowser);
use Storable qw(thaw freeze);
use Net::LDAP;
use LDAPUtils;
use Utils;
use Display;
use vars qw(@ISA);
use subs qw(exit);
# Select the correct exit function
*exit = $ENV{MOD_PERL} ? \&ModPerl::Util::exit : sub { CORE::exit };
@ISA = qw(Display);


sub new {
    my $this = shift;
    my $self = new Display(@_);
    

    return bless $self, $this;
}

sub display {
    my $this = shift;
    
    my $cgi         = $this->{"cgi"};
    my $session     = $this->{"session"};
    my $confParam   = $session->{"confParam"};
    my $sessionID   = $confParam->{"sessionID"};
    my $doit        = $cgi->param('doit');

    $this->{"ldap"} = Net::LDAP->new($confParam->{LDAPserver}, port => $confParam->{LDAPport}, version => 3);
    if(!defined $this->{"ldap"}) {
       $this->display_error("can't contact LDAP Server", "$confParam->{cgi_path}/menu.pl?sessionID=$sessionID");
       exit;
    }
    my $mesg=$this->{"ldap"}->bind ($confParam->{bind_dn}, password=>$confParam->{passwd});
    if($mesg->code != 0) {
        my $text = "bind failed\n".&LDAPerror($mesg);
        $this->display_error($text,"$confParam->{cgi_path}/menu.pl?sessionID=$sessionID");
        exit;
    }

    if(defined $doit && $doit eq "process") {
	$this->process_users();
    } else {
	$this->startup();
    }
    
    $this->{"ldap"}->unbind;

}

sub startup {
    my $this = shift;

    my $q = $this->{"cgi"};
    my $session = $this->{"session"};
    my $confParam = $session->{"confParam"};
    my $message = ($session->getLanguage($confParam->{LANG},"PROFIL","BROWSE_USER"))->data();
    my $sessionID = $confParam->{"sessionID"};

    my $action    = $q->param('action');
    my $doit      = $q->param('doit');
    my $filter    = $q->param('filter');
    my $tab       = $q->param('tab');
    my $stab      = $q->param('stab');
    my @templates = ();
    my %t_label   = ();
    my $button_width = 100;

    # Now wer looking for the templates
    my $mesg = $this->{ldap}->search (  # perform a search
                           base   => $confParam->{ubase},
                           scope  => 'one',
                           attrs => ['cn', 'uid'],
                           filter => '(role=templates)'
                          );

    foreach my $entry ($mesg->all_entries) {
            my $cn  = $entry->get_value("cn");
            my $uid = $entry->get_value("uid");
	    if( $cn ) {
		$t_label{$uid} = $cn;
	    } else {
		$t_label{$uid} = $uid;
	    }
	    push @templates, $uid;
    }
    push @templates, 'Default_User';
    $t_label{Default_User} = 'Default User';
    my $WINS = `cat /etc/samba/smb.conf | grep "logon path" | grep -q '\%a' && echo -n 1 || echo -n 0`;
    
    my $html = "";
    $html .= $q->start_table({-class=>'AdminBorder', -cellspacing=>2, -cellpadding=>0, -width=>"100%"}).
	    $q->start_Tr().
		$q->start_td().
		    $q->start_table({-cellspacing=>1, -cellpadding=>3, -width=>"100%"}).
		    $q->start_form(-action=>$confParam->{cgi_path}."/profil.pl");
    $html .=            $q->Tr( $this->help_th(2, $message->{profil}, "PROFIL"));
    $html .=            $q->Tr(
			    $q->td( $message->{choose_template}).
			    $q->td(
			    	$q->popup_menu(-name=>'template', -values=>\@templates, -labels=>\%t_label)
			    )
			);
    if ($WINS ) {
      $html .=            $q->Tr(
			    $q->td( $message->{profil_os}).
			    $q->td(
				$q->checkbox(-name=>'WinNT')." ".
				$q->checkbox(-name=>'Win2K')." ".
				$q->checkbox(-name=>'WinXP')." ".
				$q->checkbox(-name=>'Linux')
			    )
			);
    } else {
      $html .=            $q->Tr(
			    $q->td( $message->{profil_os}).
			    $q->td(
				$q->checkbox(-name=>'Windows')." ".
				$q->checkbox(-name=>'Linux')
			    )
			);
    }
    $html .=            $q->Tr(
			    $q->td( $message->{profil_readonly}).
			    $q->td(
				$q->checkbox(-name=>'read_only',-label=>'')
			    )
			);
    $html .=		$q->start_Tr().
			    $q->start_td({-align=>"center"}).
			       $q->submit(-class=>"button",-name=>"cancel",
					  -value=>"$message->{cancel}",
					  -width=>$button_width).
			       $q->hidden(-name=>"sessionID", -value=>"$sessionID").
			       $q->hidden(-name=>"action",    -value=>"$action").
			       $q->hidden(-name=>"doit",      -value=>"process").
			       $q->hidden(-name=>"filter",    -value=>"$filter").
			       $q->hidden(-name=>"filtered",  -value=>1).
			       $q->hidden(-name=>"tab",       -value=>"$tab").
			       $q->hidden(-name=>"stab",      -value=>"$stab").
			    $q->end_td().
			    $q->start_td({-align=>"center"}).
			       $q->submit(-class=>"button",-name=>"buttons",
					  -value=>"$message->{doit}",
					  -width=>$button_width ).
			    $q->end_td().
			$q->end_Tr().
		    $q->end_form().
		$q->end_table().
	    $q->end_td().
	$q->end_Tr().$q->end_table();
	
    $this->back_url("$confParam->{cgi_path}/browse_user.pl?sessionID=$sessionID\&tab=$tab\&stab=$stab\&filter=$filter\&filtered=1");
    $this->SUPER::display($html);
}

sub process_users{
    my $this = shift;

    my $q = $this->{"cgi"};
    my $session = $this->{"session"};
    my $confParam = $session->{"confParam"};
    my $message = ($session->getLanguage($confParam->{LANG},"PROFIL"))->data();
    my $sessionID = $confParam->{"sessionID"};

    my $action    = $q->param('action');
    my $doit      = $q->param('doit');
    my $filter    = $q->param('filter');
    my $tab       = $q->param('tab');
    my $stab      = $q->param('stab');
    my $stab      = $q->param('stab');
    my $template  = $q->param('template');
    my $b         = $q->param('buttons');

    my @WINS      = ();

    if( $q->param('WinXP') ) {
	push @WINS, 'WinXP';
    }
    if( $q->param('WinNT') ) {
	push @WINS, 'WinNT';
    }
    if( $q->param('Win2K') ) {
	push @WINS, 'Win2K';
    }
    if( $q->param('Windows') ) {
	push @WINS, '';
    }

    #load list of users from session
    my $frozen = $confParam->{"usersToMod"};
    if( (! defined $frozen) || ($frozen eq "") ){
        $this->display_error($message->{'error_reading_session'},
                      "$confParam->{cgi_path}/menu.pl?sessionID=$sessionID");
        exit;
    }
    $frozen = pack('H*',$frozen); # convert back to binary
    my $user_ref = thaw($frozen);     # melt down... :-)
    my @users    = @{$user_ref};
    my $text     = '';

    if(defined $b && $b eq $message->{doit}) {
	foreach my $uid (@users) {
		my $mesg;
		if( $uid ne '' ) {
		     foreach my $win (@WINS) {
                        $mesg = $session->suad_stdout_exec("rm -r /home/profile/$uid/$win" );
                        $mesg = $session->suad_mkdir("/home/profile/$uid", '700' );
                        $mesg = $session->suad_chown("/home/profile/$uid",$uid);
                        $mesg = $session->suad_stdout_exec("setfacl -d -m o::rwx /home/profile/$uid" );
                        $mesg = $session->suad_mkdir("/home/profile/$uid/$win", '700' );
			if( $template eq 'Default_User' )
			{
                           $mesg = $session->suad_copydir('/var/lib/samba/netlogon/'.$win.'/Default User',"/home/profile/$uid/$win");
			}
			else
			{
                           $mesg = $session->suad_copydir("/home/profile/$template/$win", "/home/profile/$uid/$win");
			}   
                        if( $mesg->code() ne "OK" ){
                            $text .= "profil step 2 error by user: $uid $win<br>";
                        }
                        if( $q->param('read_only') ) {
                            $mesg = $session->suad_stdout_exec("mv /home/profile/$uid/$win/ntuser.dat /home/profile/$uid/$win/ntuser.man");
                        }
                        $mesg = $session->suad_chown("/home/profile/$uid/$win",$uid);
                        $text .=  "$message->{profil_created} $uid $win<br>";
		     }
		     if( $q->param('Linux') ) {
			my $home = get_home_dir($session, $this->{ldap}, $uid);
			$mesg = $session->suad_stdout_exec("rm -r $home/Desktop/*" );
			$mesg = $session->suad_copydir("/home/templates/$template/Desktop", "$home/Desktop");
			$mesg = $session->suad_chown("/$home/Desktop",$uid);
			$text .=  "$message->{profil_created} $uid Linux<br>";
		     }
		}
	}
	if( $template ne 'Default_User' )
	{
	  my $mesg;
	  $mesg = $session->suad_chmod("/home/profile/$template/",'700');
          $mesg = $session->suad_chown("/home/profile/$template/",$template);
	}
        $this->display_msg($text, "$confParam->{cgi_path}/browse_user.pl?sessionID=$sessionID&filter=$filter&filtered=1\&tab=$tab\&stab=$stab", 5);

    } else {
	$this->display_msg($message->{abort}, 
		    "$confParam->{cgi_path}/browse_user.pl?sessionID=$sessionID&".
		    "filter=$filter&filtered=1\&tab=$tab\&stab=$stab" ,
		    1);
    }
}


1;
