#!/usr/bin/perl

$pam_dir="$ARGV[2]/etc/pam.d";

@pam_files = ("ftpd","login","passwd","sshd","su","sudo");

# Pam modules that should only check the password not get kerberos tickets:
%pam_files_no_cache = ("passwd",1,
                       "su",1,
                       "sudo",1);

#########################################################################

foreach $pam (@pam_files) {
  $pamfile = "$pam_dir/$pam";
  $skipthisfile = 0;

  $pamcontents = "";

  # Create a new security session so credentials don't go between users
  $pamcontents .= "auth       required       pam_securitysession.so\n" if ($pam_files_no_cache{$pam});

  open(PAMIN,$pamfile);
  while($thisline = <PAMIN>) {

     if ($thisline =~ /pam_krb5/o) {
        # Don't save this line since we're trying to get rid of pam_krb5
        print "removing pam_krb5 from $pamfile\n";
        next;
     }

     # Skip the whole file if pam_KFM already configured for this pam module
     if ($thisline =~ /pam_KFM/o) {
        $skipthisfile = 1;
        last;
     }

     $pamcontents .= $thisline;
     
     if ($thisline =~ /auth\s+sufficient\s+pam_securityserver.so/o) {
         # add our new line after pam_securityserver

         if ($pam_files_no_cache{$pam}) {
            $pamcontents .= "auth       sufficient     pam_KFM.so dont_cache\n";
         } else {
            $pamcontents .= "auth       sufficient     pam_KFM.so\n";
         }
     }

  }
  close(PAMIN);
 
  if ($skipthisfile) { 
     print "pam_KFM already configured for $pamfile - skipping\n";
  } else {
     print "pam_KFM: changing $pamfile\n";
     open(PAMOUT,"> $pamfile");
     print PAMOUT $pamcontents;
     close(PAMOUT);
  }
}
