#!/bin/bash

function getLDAPAttr() {
    ### Get an LDAP attribute
    # param: filter
    # param attribute
    filter="${1}"
    attribute="${2}"
    ldapsearch -x "${filter}" "${attribute}" | grep -E "^${attribute}: " | sed "s/${attribute}: //"
}

ldif="/root/cleanup.ldif"
bash="/root/cleanup.bash"
if [ "$1" == "-h" ]; then
    cat <<EOM
Usage: $0
Add -m to mute the use of ravensend.
Writes ${ldif} and ${bash} for follow-up by admins.
EOM
    exit 0
fi

# Clear cleanup files
>"${ldif}"
echo "#!/bin/bash" > "${bash}"

# Attributes
basedn=`getLDAPAttr '(cn=root)' dn | sed 's/cn=root,//'`
pwdMaxAge=`getLDAPAttr '(&(cn=default)(objectClass=pwdPolicy))' pwdMaxAge`
warning=`getLDAPAttr '(&(cn=default)(objectClass=pwdPolicy))' pwdExpireWarning`
pwdWarnAge=$(( $pwdMaxAge - $warning ))
unset EXPIRED EXPIRING OK PENDING

### Check all users
for user in `ldapsearch -x -b "ou=People,$basedn" uid | grep -E ^uid:\  | sed 's/^uid: //'`; do

    # Pull changed stats
    lastChanged=`/usr/sbin/ldapsearch -x "(uid=$user)" + | grep pwdChangedTime | cut -f 2 -d ' '`
    # created=`/usr/sbin/ldapsearch -x "(uid=$user)" + | grep createTimestamp | cut -f 2 -d ' '`
    # email=`/usr/sbin/ldapsearch -x "(uid=$user)" | grep mail | cut -f 2 -d ' '`

    # If user has PENDING changed, report
    if [ -z "$lastChanged" ]; then
        if [ -z "${PENDING}" ]; then
            PENDING="${user}"
        else
            PENDING="${PENDING},${user}"
        fi

    else
        delta="$(( `date +%s` - `date -d $(echo $lastChanged | head -c 8)  +%s`))"

        # Report if user is expired
        if [ $delta -gt $pwdMaxAge ]; then
            if [ -z "${EXPIRED}" ]; then
                EXPIRED="${user}"
            else
                EXPIRED="${EXPIRED},${user}"
            fi
            printf "dn: uid=${user},ou=People,${basedn}\nchangetype: delete\n\n" >> "${ldif}"
            printf "rm -Rf `getent passwd "${user}" | cut -f 6 -d ':'`\n" >> "${bash}"

        # Report if the user is expiring and needs to update their password.
        elif [ $delta -gt $pwdWarnAge ] && [ $delta -le $pwdMaxAge ]; then
            if [ -z "${EXPIRING}" ]; then
                EXPIRING="${user}"
            else
                EXPIRING="${EXPIRING},${user}"
            fi

        # Record the user account is OK.
        else
            if [ -z "${OK}" ]; then
                OK="${user}"
            else
                OK="${OK},${user}"
            fi
        fi
    fi

done

### Results
# Should always have OK users in the tree.
echo "OK: ${OK}"

# Report when there are users that have not changed their password.
# This may be normal, such as for new user accounts, and may not drive action.
if [ -n "$PENDING" ]; then
    echo "PENDING: ${PENDING}"
fi

# Report when users are expiring -- give them several notices to fix it.
if [ -n "${EXPIRING}" ]; then
    echo "EXPIRING: ${EXPIRING}"
    if [ "$1" != '-m' ]; then ravensend -c "#tech" -m "The following users are expiring: ${EXPIRING}"; fi
fi

# Report users that have expired. These users should be contacted or removed.
if [ -n "${EXPIRED}" ]; then
    echo "EXPIRED: ${EXPIRED}"
    echo "Expired users can be cleaned up with ${ldif} and ${bash}. Run /usr/bin/pwck and /usr/bin/grpck afterwards."
    if [ $1 != '-m' ]; then ravensend -c "#sharingan" -m 'The following users have expired and need attention.'; fi
fi
