#!/usr/bin/python3
#
# This file is part of FreedomBox.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
"""
Configuration helper for Matrix-Synapse server.
"""

import argparse

import yaml
from plinth import action_utils
from plinth.modules.matrixsynapse import CONFIG_FILE_PATH


def parse_arguments():
    """Return parsed command line arguments as dictionary"""
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers(dest='subcommand', help='Sub command')

    subparsers.add_parser('post-install', help='Perform post install steps')
    subparsers.add_parser('enable', help='Enable matrix-synapse service')
    subparsers.add_parser('disable', help='Disable matrix-synapse service')
    help_pubreg = 'Enable/Disable/Status public user registration.'
    pubreg = subparsers.add_parser('public-registration', help=help_pubreg)
    pubreg.add_argument('command', choices=('enable', 'disable', 'status'),
                        help=help_pubreg)
    setup = subparsers.add_parser('setup', help='Set domain name for Matrix')
    setup.add_argument(
        '--domain-name',
        help='The domain name that will be used by Matrix Synapse')

    subparsers.required = True
    return parser.parse_args()


def subcommand_post_install(_):
    """Perform post installation configuration."""
    with open(CONFIG_FILE_PATH) as config_file:
        config = yaml.load(config_file)

    config['max_upload_size'] = '100M'

    for listener in config['listeners']:
        if listener['port'] == 8448:
            listener['bind_address'] = '0.0.0.0'

    # Setup ldap parameters
    config['password_providers'] = [{}]
    config['password_providers'][0][
        'module'] = 'ldap_auth_provider.LdapAuthProvider'
    ldap_config = {
        'enabled': True,
        'uri': 'ldap://localhost:389',
        'start_tls': False,
        'base': 'ou=users,dc=thisbox',
        'attributes': {
            'uid': 'uid',
            'name': 'uid',
            'mail': None
        }
    }
    config['password_providers'][0]['config'] = ldap_config

    with open(CONFIG_FILE_PATH, 'w') as config_file:
        yaml.dump(config, config_file)

    if action_utils.service_is_running('matrix-synapse'):
        action_utils.service_restart('matrix-synapse')


def subcommand_setup(arguments):
    """Configure the domain name for matrix-synapse package."""
    domain_name = arguments.domain_name
    action_utils.dpkg_reconfigure('matrix-synapse', {
        'server-name': domain_name
    })
    subcommand_enable(arguments)


def subcommand_enable(_):
    """Enable service."""
    action_utils.service_enable('matrix-synapse')
    action_utils.webserver_enable('matrix-synapse-plinth')


def subcommand_disable(_):
    """Disable service."""
    action_utils.webserver_disable('matrix-synapse-plinth')
    action_utils.service_disable('matrix-synapse')


def subcommand_public_registration(argument):
    """Enable/Disable/Status public user registration."""
    with open(CONFIG_FILE_PATH) as config_file:
        config = yaml.load(config_file)

    if argument.command == 'status':
        if config['enable_registration']:
            print('enabled')
            return
        else:
            print('disabled')
            return
    elif argument.command == 'enable':
        config['enable_registration'] = True
    elif argument.command == 'disable':
        config['enable_registration'] = False

    with open(CONFIG_FILE_PATH, 'w') as config_file:
        yaml.dump(config, config_file)

    if action_utils.service_is_running('matrix-synapse'):
        action_utils.service_restart('matrix-synapse')


def main():
    arguments = parse_arguments()
    sub_command = arguments.subcommand.replace('-', '_')
    sub_command_method = globals()['subcommand_' + sub_command]
    sub_command_method(arguments)


if __name__ == '__main__':
    main()
