#!/usr/bin/python3
# -*- mode: python -*-
#
# 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 coquelicot.
"""

import argparse
import hashlib
import os
import sys

import yaml
from plinth import action_utils

SETTINGS_FILE = '/etc/coquelicot/settings.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('setup',
                          help='Post-installation operations for coquelicot')
    subparsers.add_parser('enable', help='Enable coquelicot')
    subparsers.add_parser('disable', help='Disable coquelicot')

    subparsers.add_parser(
        'set-upload-password',
        help='Set a new global, pre-shared password for uploading files')

    max_file_size = subparsers.add_parser(
        'set-max-file-size',
        help='Change the maximum size of the files that can be uploaded to '
        'Coquelicot')
    max_file_size.add_argument('size', type=int, help='upload file size in MB')

    subparsers.add_parser(
        'get-max-file-size',
        help='Print the maximum size of the files that can be uploaded to '
        'Coquelicot')

    subparsers.required = True
    return parser.parse_args()


def subcommand_setup(_):
    """Perform post-installation operations for coquelicot."""
    settings = read_settings()
    settings['path'] = "/coquelicot"
    settings['max_file_size'] = mebibytes(1024)
    write_settings(settings)
    action_utils.service_restart('coquelicot')


def subcommand_enable(_):
    """Enable web configuration and reload."""
    action_utils.service_enable('coquelicot')
    action_utils.webserver_enable('coquelicot-freedombox')


def subcommand_disable(_):
    """Disable web configuration and reload."""
    action_utils.webserver_disable('coquelicot-freedombox')
    action_utils.service_disable('coquelicot')


def subcommand_set_upload_password(arguments):
    """Set a new upload password for Coquelicot."""
    upload_password = ''.join(sys.stdin)
    settings = read_settings()
    hashed_pw = hashlib.sha1(upload_password.encode()).hexdigest()
    settings['authentication_method']['upload_password'] = hashed_pw
    write_settings(settings)
    action_utils.service_try_restart('coquelicot')


def subcommand_set_max_file_size(arguments):
    """Set a new maximum file size for Coquelicot."""
    size_in_bytes = mebibytes(arguments.size)
    settings = read_settings()
    settings['max_file_size'] = size_in_bytes
    write_settings(settings)
    action_utils.service_try_restart('coquelicot')


def subcommand_get_max_file_size(_):
    """Print the maximum file size to stdout."""
    if os.path.exists(SETTINGS_FILE):
        settings = read_settings()
        print(int(settings['max_file_size'] / (1024 * 1024)))
    else:
        print(-1)


def read_settings():
    with open(SETTINGS_FILE, 'rb') as settings_file:
        return yaml.load(settings_file)


def write_settings(settings):
    with open(SETTINGS_FILE, 'w') as settings_file:
        yaml.dump(settings, settings_file)


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

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


def mebibytes(size):
    """Return the given size of mebibytes in bytes."""
    return size * 1024 * 1024


if __name__ == '__main__':
    main()
