#!/usr/bin/python3
# -*- mode: python -*-
# SPDX-License-Identifier: AGPL-3.0-or-later
"""
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(
        '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_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()
