#!/usr/bin/env python3
#
# CherryMusic - a standalone music server
# Copyright (c) 2012 - 2016 Tom Wallroth & Tilman Boerner
#
# Project page:
#   http://fomori.org/cherrymusic/
# Sources on github:
#   http://github.com/devsnd/cherrymusic/
#
# CherryMusic is based on
#   jPlayer (GPL/MIT license) http://www.jplayer.org/
#   CherryPy (BSD license) http://www.cherrypy.org/
#
# licensed under GNU GPL version 3 (or later)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>
#

import cmbootstrap
cmbootstrap.bootstrap()
import cherrymusicserver


welcomeMessage = _("""
==========================================================================
Welcome to CherryMusic """ + cherrymusicserver.VERSION + """!

To get this party started, you need to edit the configuration file, which
resides under the following path:

    """ + cherrymusicserver.pathprovider.configurationFile() + """

Then you can start the server and listen to whatever you like.
Have fun!
==========================================================================
""")


class ConfigOptionsBase(object):
    """ Add command line options to override the cherrymusic configuration.

        It's possible to use a general option for arbitrary config keys, and
        also shortcut options which target a fixed config key. If a key is
        specified more than once, the one that got parsed last wins.

        There are two slightly different implementations, to support both
        argparse and optparse (for forward and backward compatibility).
    """
    configdict = {}

    _metavar = 'KEY=VALUE'

    @classmethod
    def addGeneralOption(cls, parser, names, help):
        kwargs = {'help': help, 'metavar': cls._metavar}
        kwargs.update(cls._config_params())
        parser.add_argument(*names, **kwargs)

    @classmethod
    def addShortcutOption(cls, parser, names, key, type, help):
        kwargs = {'help': help}
        kwargs.update(cls._shortcut_params(key, type))
        parser.add_argument(*names, **kwargs)

    @classmethod
    def _splitoption(cls, option):
        errormsg = "bad option: %r; use %r" % (option, cls._metavar)
        if not '=' in option:
            raise cls._error(option, errormsg)
        key, val = option.split('=', 1)
        if not (key and val):
            raise cls._error(errormsg)
        return key, val


try:
    import argparse

    class ConfigOptions(ConfigOptionsBase):

        @classmethod
        def _config_params(cls):
            class Action(argparse.Action):
                def __call__(self, actingparser, namespace, values, optstr):
                    for option in values:
                        try:
                            key, value = cls._splitoption(option)
                        except ValueError as e:
                            actingparser.error(e)
                        cls.configdict[key] = value
            return {'action': Action, 'nargs': '+'}

        @classmethod
        def _shortcut_params(cls, key, type=str):
            class Action(argparse.Action):
                def __call__(self, actingparser, namespace, values, optstr):
                    cls.configdict[key] = values
            return {'action': Action, 'type': type}

        @classmethod
        def _error(cls, msg):
            return ValueError(msg)

except ImportError:
    # python 3.1 and 2.6 workaround
    # since python 3.1 and python 2.6 don't have argparse, but only optparse.
    # our backport module tries to keep them compatible, but some features
    # are missing (e.g. arguments for options)
    from backport import argparse

    class ConfigOptions(ConfigOptionsBase):

        @classmethod
        def _config_params(cls):
            def callback(option, optstr, value, actingparser):
                key, value = cls._splitoption(value)
                cls.configdict[key] = value
            return {
                'action': 'callback',
                'callback': callback,
                'type': 'str',
            }

        @classmethod
        def _shortcut_params(cls, key, type=str):
            def callback(option, optstr, value, actingparser):
                cls.configdict[key] = value
            return {
                'action': 'callback',
                'callback': callback,
                'type': type.__name__,
            }

        @classmethod
        def _error(cls, msg):
            return argparse.OptionValueError(msg)


    #end of workaround

parser = argparse.ArgumentParser(description='''CherryMusic Server
Version ''' + cherrymusicserver.VERSION)

parser.add_argument('--version', dest='version', action='store_true', help='Print version information and exit.')
parser.add_argument('--info', dest='info', action='store_true', help='Print extended program information and exit.')
if 'OptionParser' in dir(argparse):
    parser.add_argument('--update', dest='update', nargs=0, default=None, help='Update the media database (get Python >= 3.2 or the argparse module to choose paths).')
else:
    parser.add_argument('--update', dest='update', nargs='*', metavar='PATH', help='Update the media database. PATH must start with basedir or be relative to basedir.')
parser.add_argument('--newconfig', dest='newconfig', action='store_true', help='Create a new config file next to your current one, e.g. ~/.config/cherrymusic/cherrymusic.conf.new.')
parser.add_argument('--dropfiledb', dest='dropfiledb', action='store_true', help='Clear the file database. This might be necessary after a version jump.')
parser.add_argument('--setup', dest='setup', action='store_true', help='Configure CherryMusic in your browser.')

parser.add_argument('--adduser', dest='adduser', nargs=2, metavar=('USERNAME', 'PASSWORD'), default=None, help='Create a new user with the given password.')
parser.add_argument('--deleteuser', dest='deleteuser', nargs=1, metavar=('USERNAME',), default=None, help='Delete a user')
parser.add_argument('--changepassword', dest='changepassword', nargs=2, metavar=('USERNAME', 'PASSWORD'), default=None, help='Change the password of a user')

ConfigOptions.addShortcutOption(parser, ('--port', '-p'), key='server.port', type=int, help='Set the port the server will listen to.')
ConfigOptions.addGeneralOption(parser, ('--conf', '-c'), help='Override configuration values.')


if __name__ == "__main__":
    import sys

    args = parser.parse_args()

    if args.info:
        print(cherrymusicserver.info())
        sys.exit(0)

    if args.version:
        print(cherrymusicserver.version())
        sys.exit(0)

    cherrymusicserver.run_general_migrations()

    if args.newconfig:
        filepath = cherrymusicserver.pathprovider.configurationFile() + '.new'
        cherrymusicserver.create_default_config_file(filepath)
        sys.exit(0)

    if args.setup:
        args.update = args.update or ()
        port = ConfigOptions.configdict.pop('server.port', False)
        from cherrymusicserver import browsersetup
        browsersetup.configureAndStartCherryPy(port) # blocks until config saved

    if not cherrymusicserver.pathprovider.configurationFileExists():
        filepath = cherrymusicserver.pathprovider.configurationFile()
        cherrymusicserver.create_default_config_file(filepath)
        print(welcomeMessage)
        sys.exit(0)

    cherrymusicserver.setup_config(ConfigOptions.configdict)
    cherrymusicserver.setup_services()

    if args.dropfiledb:
        args.update = args.update or ()
        filedb = cherrymusicserver.sqlitecache.DBNAME
        cherrymusicserver.database.resetdb(filedb)

    cherrymusicserver.migrate_databases()

    if args.adduser:
        username, password = args.adduser
        success = cherrymusicserver.create_user(username, password)
        sys.exit(0 if success else 1)

    if args.deleteuser:
        username = args.deleteuser[0]
        success = cherrymusicserver.delete_user(username)
        sys.exit(0 if success else 1)

    if args.changepassword:
        username, password = args.changepassword
        success = cherrymusicserver.change_password(username, password)
        sys.exit(0 if success else 1)

    if args.update is not None:
        cherrymusicserver.update_filedb(args.update)
        if not args.setup:
            sys.exit(0)

    cherrymusicserver.start_server(ConfigOptions.configdict)
