#!/tmp/codtest/bin/python
#
# Hey Emacs, this is -*-python-*-
#
# Copyright 2013-2014 Peter Liljenberg <peter.liljenberg@gmail.com>
#
# Distributed under an MIT license, please see LICENSE in the top dir.

import sys
import os
import argparse


# http://www.python.org/dev/peps/pep-3143/
import daemon
import lockfile

from codplayer import db, player, config, sink
from codplayer import command

def main(args):
    try:
        # As a general principle, parse as much config and open as
        # many resources as possible before forking off a deamon
        # process.  The flipside of that is that we must keep track of
        # the files that should be kept open across the daemonization
        preserve_files = []

        cfg = config.PlayerConfig(args.config)
        database = db.Database(cfg.database)

        if cfg.audio_device_type not in sink.SINKS:
            sys.exit('unknown audio device type: {0}'.format(cfg.audio_device_type))

        if args.debug:
            log_file = sys.stderr
            cfg.commands.append(command.StdinCommandFactory())
        else:
            try:
                log_file = open(cfg.log_file, 'at')
            except IOError, e:
                sys.exit('error opening {0}: {1}'.format(cfg.log_file, e))

            preserve_files.append(log_file)

        # All set, create the player object
        p = player.Player(cfg, database, log_file)

    except config.ConfigError, e:
        sys.exit('invalid configuration:\n{0}'.format(e))

    except db.DatabaseError, e:
        sys.exit('error opening database:\n{0}'.format(e))

    if args.debug:
        # Just run directly without forking off
        p.run()
    else:
        context = daemon.DaemonContext(
            files_preserve = preserve_files,
            pidfile = lockfile.FileLock(cfg.pid_file),
            stdout = log_file,
            stderr = log_file,
            )

        # Run in daemon context, forking off and all that
        with context:
            p.run()

    
#
# Set up the command argument parsing
#

parser = argparse.ArgumentParser(description = 'codplayer daemon')
parser.add_argument('-c', '--config', help = 'alternative configuration file')
parser.add_argument('-d', '--debug', action = 'store_true',
                    help = 'run in debug mode instead of deamon')

if __name__ == '__main__':
    args = parser.parse_args()
    main(args)
