#!/usr/bin/env python
# -*- coding: utf-8; -*-
#
# (c) 2004-2007 Linbox / Free&ALter Soft, http://linbox.com
# (c) 2007-2012 Mandriva, http://www.mandriva.com/
#
# This file is part of Mandriva Management Console (MMC).
#
# MMC is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# MMC is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with MMC; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

"""
A simple cronjob for checking expired user passwords

if RESET_BLOCKED_USERS_PASSWORDS is True, the script will
set a new password to users that can't change their passwords
anymore. (the mmc-check-password package must be installed)

Mails are sent to notify the users

"""

RESET_BLOCKED_USERS_PASSWORDS = True
SEND_MAILS = False
SUPPORT = "support@example.com"
SMTP = "localhost"
MMC_URL = "http://localhost/mmc"


from mmc.plugins.ppolicy import isPasswordExpired, isAccountInGraceLogin, getUserPPolicy, getDefaultPPolicy, getPPolicy
from mmc.plugins.base import getUsersLdap, changeUserPasswd
from mmc.support.mmctools import shlaunch
import smtplib
from email.mime.text import MIMEText


for user in getUsersLdap():

    body = None
    uid = user['uid']
    mail = user['mail']
    isExpired = isPasswordExpired(user['uid'])
    nbGraceLogins = isAccountInGraceLogin(user['uid'])

    ppolicy_name = getUserPPolicy(uid)
    if not ppolicy_name:
        ppolicy = getDefaultPPolicy()[1]
    else:
        ppolicy = getPPolicy(ppolicy_name)[1]

    if 'pwdMinLength' in ppolicy:
        min_length = ppolicy['pwdMinLength'][0]
    else:
        min_length = 6

    if nbGraceLogins == -1:
        if 'pwdGraceAuthNLimit' in ppolicy:
            nbGraceLogins = int(ppolicy['pwdGraceAuthNLimit'][0])
        else:
            nbGraceLogins = 0

    if isExpired and nbGraceLogins in (0, 1):
        # User can't change its password
        # Change the password for him
        print "Password blocked for user %s" % uid
        if RESET_BLOCKED_USERS_PASSWORDS and mail:
            new_pass = shlaunch('mmc-password-helper -n -l %s' % min_length)[0]
            changeUserPasswd(uid, new_pass)
            subject = "[Warning] Password changed"
            body = """
Your password was changed because it has expired.

Your new password is : %s

__
%s
""" % (new_pass, SUPPORT)
            print "Password changed for user %s (%s)" % (uid, new_pass)
        elif RESET_BLOCKED_USERS_PASSWORDS and not mail:
            print "User %s has no mail. Can't change password." % uid

    if isExpired and (nbGraceLogins > 1 or nbGraceLogins == -1):
        print "Password expired for user %s" % uid
        # User can change its password
        subject = "[Warning] Password has expired"
        body = """
Your password has expired. You have only %s logins left.

Change your password at %s as soon as possible.

__
%s

""" % (str(nbGraceLogins-1), MMC_URL, SUPPORT)

    if body and SEND_MAILS:
        msg = MIMEText(body)
        msg['Subject'] = subject
        msg['From'] = SUPPORT
        msg['To'] = mail
        s = smtplib.SMTP(SMTP)
        s.sendmail(SUPPORT, mail, msg.as_string())
        s.quit()
        print "Mail sent to %s" % mail
