#!/bin/bash

addNoLogin()
{
  PAMFILE=$1
  TMPFILE=/tmp/pamd.tmp.$$
  /usr/bin/grep -q "pam_nologin.so" $PAMFILE
  if [ $? -ne 0 ]; then
     >${TMPFILE}
     while read line
     do
       module=`echo ${line} | awk '{print $3}'`
       if [ -n "${module}" ]; then
   	  module=`/usr/bin/basename "${module}"`
       fi
       echo ${line} >> ${TMPFILE}
       if [ "${module}" = "common-auth" ]; then
	  echo "auth     required       pam_nologin.so" >> ${TMPFILE}
       fi
     done < $PAMFILE
     /bin/mv -f ${TMPFILE} $1
   fi
}

addCommon()
{
  PAMFILE=$1
  TMPFILE=/tmp/pamd.tmp.$$
  >${TMPFILE}
  while read line
  do
       module=`echo ${line} | awk '{print $3}'`
       if [ -n "${module}" ]; then
   	  module=`/usr/bin/basename "${module}"`
       fi
       if [ "${module}" = "pam_unix_auth.so" ]; then
	  echo "auth sufficient /lib/security/pam_unix_auth.so" >> ${TMPFILE}
	  /usr/bin/grep -q "pam_krb5" ${PAMFILE}
	  if [ $? -ne 0 ]; then
	    echo "auth sufficient /lib/security/pam_krb5.so search_k5login use_first_pass use_authtok" >>${TMPFILE}
	  fi
	  /usr/bin/grep -q "pam_ldap" ${PAMFILE}
	  if [ $? -ne 0 ]; then
            echo "auth required /lib/security/pam_ldap.so use_first_pass config=/etc/openldap/ldap.conf" >>${TMPFILE} 
	  fi
        else
           echo ${line} >>${TMPFILE}
        fi
  done < $PAMFILE
  /bin/mv -f ${TMPFILE} $1
}

removeKRB()
{
  PAMFILE=$1
  TMPFILE=/tmp/pamd.tmp.$$
  /usr/bin/grep -q "pam_krb5.so" $PAMFILE
  if [ $? -eq 0 ]; then
    >${TMPFILE}
    while read line
    do
       module=`echo ${line} | awk '{print $3}'`
       if [ -n "${module}" ]; then
   	  module=`/usr/bin/basename "${module}"`
       fi
       if [ "${module}" != "pam_krb5.so" ]; then
          echo ${line} >> ${TMPFILE}
       fi
    done < $PAMFILE
    /bin/mv -f ${TMPFILE} $1
  fi
}

removeLDAP()
{
  PAMFILE=$1
  TMPFILE=/tmp/pamd.tmp.$$
  /usr/bin/grep -q "pam_ldap.so" $PAMFILE
  if [ $? -eq 0 ]; then
     >${TMPFILE}
     while read line
     do
       module=`echo ${line} | awk '{print $3}'`
       if [ -n "${module}" ]; then
   	  module=`/usr/bin/basename "${module}"`
       fi
       if [ "${module}" != "pam_ldap.so" ]; then
          echo ${line} >> ${TMPFILE}
       fi
     done < $PAMFILE
     /bin/mv -f ${TMPFILE} $1
  fi
}

# setup PAM file to have Kerberos and Ldap
removeKRB /etc/pam.d/sshd
removeKRB /etc/pam.d/ipauth
removeKRB /etc/pam.d/wbem

removeLDAP /etc/pam.d/sshd
removeLDAP /etc/pam.d/ipauth
removeLDAP /etc/pam.d/wbem

addNoLogin /etc/pam.d/sshd
addNoLogin /etc/pam.d/ipauth
addCommon /etc/pam.d/common-auth
addCommon /etc/pam.d/wbem
exit 0

