package lib_module_password;

use Exporter;

use vars qw/@ISA @EXPORT/;

@ISA = qw/Exporter/;
@EXPORT = qw/AddUser AddGroup/;

use lib_module_common;

sub AddUser($$$$$);
sub AddGroup($;@);

use strict;

sub AddUser($$$$$) {
  my ($user, $gid, $home, $pw, $uid) = @_;
  my $days_since_1970 = int(time() / 86400); #/
  if($pw eq ''){
    $pw = '*';
  }
  else{
    my $salt = substr($pw, 0, 2);
    $pw = crypt($pw, $salt);
  }
  print &ltext('install_useradd', $user);
  open(SHADOW, '>>', $main::shadowDir );
  open(PASSWD, '>>', $main::passwdDir );
  if ($main::OSTYPE eq 'Linux'){
    print PASSWD "$user\:x:$uid\:$gid\::$home\:/bin/false\n";
    print SHADOW "$user\:$pw\:$days_since_1970\:0:99999::::\n";
  }
  elsif ($main::OSTYPE eq 'FreeBSD'){
    print PASSWD "$user\:*:$uid\:$gid\::$home\:/bin/false\n";
    print SHADOW "$user\:$pw\:$uid\:$gid\::0:0::$home\:/bin/false\n\n";
    system("/usr/sbin/pwd_mkdb -d /etc /etc/master.passwd");
  }
  close(PASSWD);
  close(SHADOW);
}

# add group to /etc/group with its members
# arg $group - name of group
# arg @members - array/list of group members
sub AddGroup ($;@) {
  my($group, @members) = @_;
  
  my($gid, %gid, $i, $stop);
  $gid = getgrnam($group);
  if(defined $gid && $gid =~ /^\d+$/){
    $i = $gid;
    if(@members){
      my (@lines,$pattern,$prefix,$suffix,%items,$npp,$item,$wasAdd);
      $pattern = qr/^(\Q$group\E:[^:]*:\d+:)(.*)/;
      if(open(GROUP, '<', $main::groupDir ) ) {
				while(<GROUP>){
# find line of $group
					if($_ =~ /$pattern/){
						$prefix=$1;
						$suffix = $2;
						$npp=0;
						chomp $suffix;
						%items = map {$_=>$npp++} split(/\s*,\s*/,$suffix);
# check if $group has all @members
						foreach $item (@members){
							unless(exists($items{$item})){
								$wasAdd=1;
								$items{$item}=$npp++;
							}
						}
						$suffix = join(',',keys %items);
						push @lines,$prefix.$suffix."\n";
					}else{
						push @lines,$_;
					}
				}
				close (GROUP);
				if($wasAdd){
#
# save new memebers to group
#
					if(open(GROUP,'>', $main::groupDir ) ) {
						foreach $item (@lines){
							print GROUP $item;
						}
						close (GROUP);
					}
				}
      }
    }

  } else {
    open(GROUP, '<', $main::groupDir );
    while(<GROUP>){
      if($_ =~ /^[^:]+:[^:]*:(\d+):/){
        $gid{$1} = 1;
      }
    }
    close(GROUP);
    $stop = 0;
    $i = "500";
    while(defined $gid{$i}){
      $i++;
    }
    print &ltext('install_groupadd', $group);
		my $members_str = join(',', @members);
    open(GROUP, '>>', $main::groupDir );
    print GROUP "$group:x:$i:$members_str\n";
    close(GROUP);
  }


  return($i);
}

1;
