#!/usr/bin/python3
#
# 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 Tiny Tiny RSS.
"""

import argparse
import augeas
import subprocess

from plinth import action_utils

CONFIG_FILE = '/etc/tt-rss/config.php'
DEFAULT_FILE = '/etc/default/tt-rss'
DATABASE_FILE = '/etc/tt-rss/database.php'


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-setup', help='Perform pre-setup operations')
    subparsers.add_parser('setup', help='Setup Tiny Tiny RSS configuration')
    subparsers.add_parser('enable', help='Enable Tiny Tiny RSS site')
    subparsers.add_parser('disable', help='Disable Tiny Tiny RSS site')

    subparsers.required = True
    return parser.parse_args()


def subcommand_pre_setup(_):
    """Preseed debconf values before packages are installed."""
    subprocess.check_output(
        ['debconf-set-selections'],
        input=b'tt-rss tt-rss/database-type string pgsql')


def subcommand_setup(_):
    """Setup Tiny Tiny RSS configuration."""
    aug = load_augeas()

    aug.set('/files' + DEFAULT_FILE + '/DISABLED', '0')

    for match in aug.match('/files' + CONFIG_FILE + '/define'):
        if aug.get(match) == 'SELF_URL_PATH':
            aug.set(match + '/value', "'http://localhost/tt-rss/'")
        elif aug.get(match) == 'PLUGINS':
            aug.set(match + '/value', "'auth_remote, note'")

    aug.save()

    action_utils.service_restart('tt-rss')
    action_utils.webserver_enable('tt-rss-plinth')
    enable_api_access()


def enable_api_access():
    """Enable API access so that tt-rss can be accessed through mobile app."""
    import psycopg2  # Only available post installation

    aug = load_augeas()

    def get_value(variable_name):
        """Return the value of a variable from database configuration file."""
        return aug.get('/files' + DATABASE_FILE + '/$' + variable_name) \
            .strip("'\"")

    user = get_value('dbuser')
    password = get_value('dbpass')
    database = get_value('dbname')
    host = get_value('dbserver')

    connection = psycopg2.connect(
        database=database, user=user, password=password, host=host)
    cursor = connection.cursor()

    cursor.execute("UPDATE ttrss_prefs SET def_value=true "
                   "WHERE pref_name='ENABLE_API_ACCESS';")

    connection.commit()
    connection.close()


def subcommand_enable(_):
    """Enable web configuration and reload."""
    action_utils.service_enable('tt-rss')
    action_utils.webserver_enable('tt-rss-plinth')


def subcommand_disable(_):
    """Disable web configuration and reload."""
    action_utils.webserver_disable('tt-rss-plinth')
    action_utils.service_disable('tt-rss')


def load_augeas():
    """Initialize Augeas."""
    aug = augeas.Augeas(flags=augeas.Augeas.NO_LOAD +
                        augeas.Augeas.NO_MODL_AUTOLOAD)
    aug.set('/augeas/load/Shellvars/lens', 'Shellvars.lns')
    aug.set('/augeas/load/Shellvars/incl[last() + 1]', DEFAULT_FILE)
    aug.set('/augeas/load/Phpvars/lens', 'Phpvars.lns')
    aug.set('/augeas/load/Phpvars/incl[last() + 1]', CONFIG_FILE)
    aug.set('/augeas/load/Phpvars/incl[last() + 1]', DATABASE_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()
