#!/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: selinux
# configure: 30
# description: Script to configure template selinux.
### END PLUGIN INFO

import json
import re

from templateconfig.cli import main
from templateconfig.common import shell_cmd


def do_enumerate(target):
    param = []
    if target == 'configure':
        param += [{'key': 'com.oracle.linux.selinux.mode',
                   'description': 'SELinux mode: enforcing, permissive or disabled.',
                   'hidden': True}]
    return json.dumps(param)


def do_configure(param):
    param = json.loads(param)
    mode = param.get('com.oracle.linux.selinux.mode', '').strip()
    if mode in ['enforcing', 'permissive', 'disabled']:
        config = open('/etc/selinux/config', "r+")
        content = config.read()
        if re.search(r'(^|\n)SELINUX=.*', content):
            content = re.sub(r'(^|\n)SELINUX=.*', r'\1SELINUX=%s' % mode, content)
        else:
            content += "\nSELINUX=%s" % mode
        config.seek(0)
        config.truncate(0)
        config.write(content)
        config.close()
        (rc, m, _) = shell_cmd('getenforce')
        if rc == 0:
            if mode != m.lower():
                if mode in ['permissive', 'disabled']:
                    shell_cmd('setenforce Permissive')
                else:
                    shell_cmd('setenforce Enforcing')
    return json.dumps(param)


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