#!/usr/libexec/platform-python

# Copyright (C) 2011 Oracle. All rights reserved.
#
# This program 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, version 2.  This program 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 this program; if not, write to the Free
# Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
# 021110-1307, USA.

### BEGIN PLUGIN INFO
# name: user
# configure: 60
# cleanup: 40
# description: Script to configure template user.
### END PLUGIN INFO

import grp
import json
import pwd

from templateconfig.cli import main
from templateconfig.common import run_cmd, shell_cmd, get_entry_list, set_password


def groupadd(param):
    for (name, index) in get_entry_list(param, 'com.oracle.linux.group.name'):
        action = param.get('com.oracle.linux.group.action.%s' % index)
        if action not in ['add', 'del', 'mod']:
            raise Exception('Unknown group action: %s' % action)
        if action == 'add':
            cmd = ['groupadd']
            gid = param.get('com.oracle.linux.group.gid.%s' % index)
            if gid:
                cmd += ['-g', gid]
            cmd += [name]
            run_cmd(cmd)


def groupmod(param):
    for (name, index) in get_entry_list(param, 'com.oracle.linux.group.name'):
        action = param.get('com.oracle.linux.group.action.%s' % index)
        if action not in ['add', 'del', 'mod']:
            raise Exception('Unknown group action: %s' % action)
        if action == 'mod':
            cmd = ['groupmod']
            gid = param.get('com.oracle.linux.group.gid.%s' % index)
            if gid:
                cmd += ['-g', gid]
            new_name = param.get('com.oracle.linux.group.new-name.%s' % index)
            if new_name:
                cmd += ['-n', new_name]
            if gid or new_name:
                cmd += [name]
                run_cmd(cmd)


def groupdel(param):
    for (name, index) in get_entry_list(param, 'com.oracle.linux.group.name'):
        action = param.get('com.oracle.linux.group.action.%s' % index)
        if action not in ['add', 'del', 'mod']:
            raise Exception('Unknown group action: %s' % action)
        if action == 'del':
            try:
                grp.getgrnam(name)
            except KeyError:
                continue
            cmd = ['groupdel', name]
            run_cmd(cmd)


def useradd(param):
    for (name, index) in get_entry_list(param, 'com.oracle.linux.user.name'):
        action = param.get('com.oracle.linux.user.action.%s' % index)
        if action not in ['add', 'del', 'mod']:
            raise Exception('Unknown user action: %s' % action)
        if action == 'add':
            cmd = ['useradd']
            uid = param.get('com.oracle.linux.user.uid.%s' % index)
            if uid:
                cmd += ['-u', uid]
            group = param.get('com.oracle.linux.user.group.%s' % index)
            if group:
                cmd += ['-g', group]
            groups = param.get('com.oracle.linux.user.groups.%s' % index)
            if groups:
                cmd += ['-G', groups]
            cmd += [name]
            run_cmd(cmd)
            password = param.get('com.oracle.linux.user.password.%s' % index)
            if password is not None:
                set_password(name, password)


def usermod(param):
    for (name, index) in get_entry_list(param, 'com.oracle.linux.user.name'):
        action = param.get('com.oracle.linux.user.action.%s' % index)
        if action not in ['add', 'del', 'mod']:
            raise Exception('Unknown user action: %s' % action)
        elif action == 'mod':
            cmd = ['usermod']
            uid = param.get('com.oracle.linux.user.uid.%s' % index)
            if uid:
                cmd += ['-u', uid]
            group = param.get('com.oracle.linux.user.group.%s' % index)
            if group:
                cmd += ['-g', group]
            groups = param.get('com.oracle.linux.user.groups.%s' % index)
            if groups:
                cmd += ['-G', groups]
            new_name = param.get('com.oracle.linux.user.new-name.%s' % index)
            if new_name:
                cmd += ['-l', new_name]
            if uid or group or groups or new_name:
                cmd += [name]
                run_cmd(cmd)
            password = param.get('com.oracle.linux.user.password.%s' % index)
            if password is not None:
                set_password(name, password)


def userdel(param):
    for (name, index) in get_entry_list(param, 'com.oracle.linux.user.name'):
        action = param.get('com.oracle.linux.user.action.%s' % index)
        if action not in ['add', 'del', 'mod']:
            raise Exception('Unknown user action: %s' % action)
        if action == 'del':
            try:
                pwd.getpwnam(name)
            except KeyError:
                continue
            cmd = ['userdel', '-r', name]
            run_cmd(cmd)


def do_enumerate(target):
    param = []
    if target == 'configure':
        param += [{'key': 'com.oracle.linux.user.name.0',
                   'description': 'Name of the user on which to perform operation.',
                   'hidden': True},
                  {'key': 'com.oracle.linux.user.action.0',
                   'description': 'Action to perform on the user: add, del or mod.',
                   'hidden': True},
                  {'key': 'com.oracle.linux.user.uid.0',
                   'description': 'User ID.',
                   'hidden': True},
                  {'key': 'com.oracle.linux.user.group.0',
                   'description': 'User initial login group.',
                   'hidden': True},
                  {'key': 'com.oracle.linux.user.groups.0',
                   'description': 'Supplementary groups separated by comma.',
                   'hidden': True},
                  {'key': 'com.oracle.linux.user.password.0',
                   'description': 'User password.',
                   'password': True,
                   'hidden': True},
                  {'key': 'com.oracle.linux.user.new-name.0',
                   'description': 'New name of the user.',
                   'hidden': True},
                  {'key': 'com.oracle.linux.group.name.0',
                   'description': 'Name of the group on which to perform operation.',
                   'hidden': True},
                  {'key': 'com.oracle.linux.group.action.0',
                   'description': 'Action to perform on the group: add, del or mod.',
                   'hidden': True},
                  {'key': 'com.oracle.linux.group.gid.0',
                   'description': 'Group ID.',
                   'hidden': True},
                  {'key': 'com.oracle.linux.group.new-name.0',
                   'description': 'New name of the group.',
                   'hidden': True}]
    return json.dumps(param)


def do_configure(param):
    param = json.loads(param)
    groupadd(param)
    useradd(param)
    groupmod(param)
    usermod(param)
    userdel(param)
    groupdel(param)
    return json.dumps(param)


def do_cleanup(param):
    param = json.loads(param)
    for userinfo in pwd.getpwall():
        homedir = userinfo[5]
        shell_cmd('rm -fr %s/.bash_history' % homedir)
    return json.dumps(param)


if __name__ == '__main__':
    main(do_enumerate, {'configure': do_configure, 'cleanup': do_cleanup})
