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

import argparse
import augeas

from plinth import action_utils

CONFIG_FILE = '/etc/minetest/minetest.conf'
AUG_PATH = '/files' + CONFIG_FILE + '/.anon'


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

    configure = subparsers.add_parser('configure', help='Configure Minetest')
    configure.add_argument('--max_players',
                           help='Set maximum number of players')
    configure.add_argument('--creative_mode', choices=['true', 'false'],
                           help='Set creative mode true/false')
    configure.add_argument('--enable_pvp', choices=['true', 'false'],
                           help='Set player Vs player true/false')
    configure.add_argument('--enable_damage', choices=['true', 'false'],
                           help='Set damage true/false')

    subparsers.required = True
    return parser.parse_args()


def subcommand_configure(arguments):
    """Configure Minetest."""
    aug = load_augeas()

    if arguments.max_players:
        set_max_players(aug, arguments.max_players)
    if arguments.creative_mode:
        set_creative_mode(aug, arguments.creative_mode)
    if arguments.enable_pvp:
        enable_pvp(aug, arguments.enable_pvp)
    if arguments.enable_damage:
        enable_damage(aug, arguments.enable_damage)

    action_utils.service_restart('minetest-server')


def set_max_players(aug, max_players):
    """Sets the number of max players"""
    aug.set(AUG_PATH + '/max_users', max_players)
    aug.save()


def enable_pvp(aug, choice):
    """Enables pvp"""
    aug.set(AUG_PATH + '/enable_pvp', choice)
    aug.save()


def set_creative_mode(aug, choice):
    """Enables or disables creative mode"""
    aug.set(AUG_PATH + '/creative_mode', choice)
    aug.save()


def enable_damage(aug, choice):
    """Enables damage"""
    aug.set(AUG_PATH + '/enable_damage', choice)
    aug.save()


def load_augeas():
    """Initialize Augeas."""
    aug = augeas.Augeas(flags=augeas.Augeas.NO_LOAD +
                        augeas.Augeas.NO_MODL_AUTOLOAD)
    aug.set('/augeas/load/Php/lens', 'Php.lns')
    aug.set('/augeas/load/Php/incl[last() + 1]', CONFIG_FILE)
    aug.load()
    return aug


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()
