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

import argparse
import json
import pathlib
import shutil
import subprocess

from plinth.modules import calibre

LIBRARIES_PATH = pathlib.Path('/var/lib/calibre-server-freedombox/libraries')


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('list-libraries',
                          help='Return the list of libraries setup')
    subparser = subparsers.add_parser('create-library',
                                      help='Create an empty library')
    subparser.add_argument('name', help='Name of the new library')
    subparser = subparsers.add_parser('delete-library',
                                      help='Delete a library and its contents')
    subparser.add_argument('name', help='Name of the library to delete')

    subparsers.required = True
    return parser.parse_args()


def subcommand_list_libraries(_):
    """Return the list of libraries setup."""
    libraries = []
    for library in LIBRARIES_PATH.glob('*/metadata.db'):
        libraries.append(str(library.parent.name))

    print(json.dumps({'libraries': libraries}))


def subcommand_create_library(arguments):
    """Create an empty library."""
    calibre.validate_library_name(arguments.name)
    library = LIBRARIES_PATH / arguments.name
    library.mkdir(mode=0o755)  # Raise exception if already exists
    subprocess.call(
        ['calibredb', '--with-library', library, 'list_categories'],
        stdout=subprocess.DEVNULL)

    # Force systemd StateDirectory= logic to assign proper ownership to the
    # DynamicUser=
    shutil.chown(LIBRARIES_PATH.parent, 'root', 'root')


def subcommand_delete_library(arguments):
    """Delete a library and its contents."""
    calibre.validate_library_name(arguments.name)
    library = LIBRARIES_PATH / arguments.name
    shutil.rmtree(library)


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