#!/usr/bin/python3
# SPDX-License-Identifier: AGPL-3.0-or-later
"""
Configuration helper for diaspora* pod.
"""

import argparse
import subprocess

import augeas

from plinth import action_utils
from plinth.modules import diaspora

DIASPORA_YAML = "/etc/diaspora/diaspora.yml"


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(
        'pre-install',
        help='Preseed debconf values before packages are installed.')
    subparsers.add_parser(
        'enable-user-registrations',
        help='Allow users to sign up to this diaspora* pod without an '
        'invitation.')
    subparsers.add_parser(
        'disable-user-registrations',
        help='Allow only users with an invitation to register to this '
        'diaspora* pod')
    subparsers.add_parser('start-diaspora', help='Start diaspora* service')
    subparsers.add_parser(
        'disable-ssl', help="Disable SSL on the diaspora* application server")
    setup = subparsers.add_parser('setup',
                                  help='Set Domain name for diaspora*')
    setup.add_argument('--domain-name',
                       help='The domain name that will be used by diaspora*')

    return parser.parse_args()


def subcommand_setup(arguments):
    """Set the domain_name in diaspora configuration files"""
    domain_name = arguments.domain_name
    with open('/etc/diaspora/domain_name', 'w') as dnf:
        dnf.write(domain_name)
    set_domain_name(domain_name)
    uncomment_user_registrations()


def set_domain_name(domain_name):
    """Write a new domain name to diaspora configuration files"""
    # This did not set the domain_name
    # action_utils.dpkg_reconfigure('diaspora-common',
    #                               {'url': domain_name})
    # Manually changing the domain name in the conf files.
    conf_file = '/etc/diaspora.conf'
    aug = augeas.Augeas(flags=augeas.Augeas.NO_LOAD +
                        augeas.Augeas.NO_MODL_AUTOLOAD)

    # lens for shell-script config file
    aug.set('/augeas/load/Shellvars/lens', 'Shellvars.lns')
    aug.set('/augeas/load/Shellvars/incl[last() + 1]', conf_file)
    aug.load()

    aug.set('/files/etc/diaspora.conf/SERVERNAME', '"{}"'.format(domain_name))
    aug.set('/files/etc/diaspora.conf/ENVIRONMENT_URL',
            'http://{}:3000'.format(domain_name))
    aug.save()

    diaspora.generate_apache_configuration(
        '/etc/apache2/conf-available/diaspora-plinth.conf', domain_name)

    action_utils.service_enable('diaspora')
    action_utils.service_start('diaspora')


def subcommand_disable_ssl(_):
    """
    Disable ssl in the diaspora configuration
    as the apache server takes care of ssl
    """
    # Using sed because ruamel.yaml has a bug for this kind of files
    subprocess.call([
        "sed", "-i", "s/#require_ssl: true/require_ssl: false/g", DIASPORA_YAML
    ])


def uncomment_user_registrations():
    """Uncomment the enable_registrations line which is commented by default"""
    subprocess.call([
        "sed", "-i", "s/#enable_registrations/enable_registrations/g",
        DIASPORA_YAML
    ])


def subcommand_enable_user_registrations(_):
    """Enable new user registrations on the diaspora* pod """
    subprocess.call([
        "sed", "-i",
        "s/enable_registrations: false/enable_registrations: true/g",
        DIASPORA_YAML
    ])


def subcommand_disable_user_registrations(_):
    """Disable new user registrations on the diaspora* pod """
    subprocess.call([
        "sed", "-i",
        "s/enable_registrations: true/enable_registrations: false/g",
        DIASPORA_YAML
    ])


def subcommand_pre_install(_):
    """Pre installation configuration for diaspora"""
    presets = [
        'diaspora-common diaspora-common/url string dummy_domain_name',
        'diaspora-common diaspora-common/dbpass note ',
        'diaspora-common diaspora-common/enablessl boolean false',
        'diaspora-common diaspora-common/useletsencrypt string false',
        'diaspora-common diaspora-common/services multiselect ',
        'diaspora-common diaspora-common/ssl boolean false',
        'diaspora-common diaspora-common/pgsql/authmethod-admin string ident',
        'diaspora-common diaspora-common/letsencrypt boolean false',
        'diaspora-common diaspora-common/remote/host string localhost',
        'diaspora-common diaspora-common/database-type string pgsql',
        'diaspora-common diaspora-common/dbconfig-install boolean true'
    ]

    action_utils.debconf_set_selections(presets)


def main():
    """Parse arguments and perform all duties."""
    arguments = parse_arguments()

    subcommand = arguments.subcommand.replace('-', '_')
    subcommand_method = globals()['subcommand_' + subcommand]
    subcommand_method(arguments)


if __name__ == '__main__':
    main()
