#!/usr/bin/perl

use strict;

if ($#ARGV != 1) 
  {
  print "Usage: $0 username newpassword\n" ;
  return(1);
  }

my $actuser = shift;
my $actpass = shift;

my $err = &change_password($actuser,$actpass);
print "Code $err\n";

exit 0;


sub change_password # (user, newpass)
  {
  # Gegebenenfalls sind die Pfade von 'cp' und 'sed' anzupassen!
  #
  # can only be done as root
  # Errorcodes:
  #   0  O.K.
  #   1  User does not exist
  #   2  More than one user
  #   3  Error while copying $passwd to $ptmp
  #   4  Changing $ptmp failed
  #   5  Error while copying $ptmp to $passwd

  my $user = @_[0];
  my $newpass = @_[1];
  my @saltset = ('a' .. 'z', 'A' .. 'Z', '0' .. '9', '.', '/');
  my $ptmp = '/etc/ptmp';
  my $passwd = '/etc/shadow';
  my @entry = ();
  my @rest=();
  my $name = '';
  my $oldcrypt = '';
  my $newcrypt = '';
  my $salt = '';
  my $ok = '';
  my $line = '';
  
  srand(time|$$);
  open(PASSWD,'<' . $passwd);
  @entry = grep(/^$user:/,<PASSWD>);
  close PASSWD;
  return(1) if ($#entry == -1); 
  return(2) if ($#entry != 0); 
  $line = shift(@entry);
  ($name, $oldcrypt, @rest) = split(/:/, $line);
  $salt = $saltset[rand(62)] . $saltset[rand(62)];    # form new salt
  $newcrypt = crypt($newpass,$salt);  	# form new encrypted password
  
  sleep(2) while ( -f $ptmp ); 
  $ok = system("/bin/cp $passwd $ptmp");
  return(3) if ($ok != 0); 
  $ok = system("/usr/bin/sed -e 's/^$user:$oldcrypt:/$user:$newcrypt:/' $passwd > $ptmp");
  if ($ok != 0) 
    {
    unlink($ptmp);
    return(4);
    }
  $ok = system("/bin/cp $ptmp $passwd");
  if ($ok != 0) 
    {
    print "RED ALERT! Couldn't update $passwd. Backup file is $ptmp\n";
    return(5);
    }
  unlink($ptmp);
  return(0);	
  } 
  
  
  
  
