#!/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/>.
#
"""
Helper script for configuring Shadowsocks.
"""

import argparse
import json
import os
import sys

from plinth import action_utils
from plinth.modules import shadowsocks

SHADOWSOCKS_CONFIG = '/etc/shadowsocks-libev/freedombox.json'


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='Perform initial setup steps')
    subparsers.add_parser(
        'get-config', help='Read and print JSON config to stdout')
    subparsers.add_parser(
        'merge-config', help='Merge JSON config from stdin with existing')

    subparsers.required = True
    return parser.parse_args()


def subcommand_setup(_):
    """Perform initial setup steps."""
    # Only client socks5 proxy is supported for now. Disable the
    # server component.
    action_utils.service_disable('shadowsocks-libev')


def subcommand_get_config(arguments):
    """Read and print Shadowsocks configuration."""
    try:
        print(open(SHADOWSOCKS_CONFIG, 'r').read())
    except Exception:
        sys.exit(1)


def subcommand_merge_config(arguments):
    """Configure Shadowsocks."""
    config = sys.stdin.read()
    config = json.loads(config)

    try:
        current_config = open(SHADOWSOCKS_CONFIG, 'r').read()
        current_config = json.loads(current_config)
    except (OSError, json.JSONDecodeError):
        current_config = {}

    new_config = current_config
    new_config.update(config)
    new_config = json.dumps(new_config, indent=4, sort_keys=True)

    old_umask = os.umask(0o027)
    try:
        open(SHADOWSOCKS_CONFIG, 'w').write(new_config)
    finally:
        os.umask(old_umask)

    action_utils.service_restart(shadowsocks.managed_services[0])


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