#!/usr/bin/python

# This file is part of vdr-webvideo-plugin.
#
# Copyright 2009 Antti Ajanki <antti.ajanki@iki.fi>
#
# 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 logging
import sys
import socket
from optparse import OptionParser
from webvidaemon import webvidaemon, daemonize, asyncurl

DEFAULT_PORT = 2357
DEFAULT_SERVICE_PATH = '/usr/share/webvid'
DEFAULT_LOG_FILE = '/tmp/webvid.log'
DEFAULT_PID_FILE = '/var/run/webvid.pid'

def setup_logging(filename=None):
    log = logging.getLogger('webvid')
    if (filename is None) or (filename == ''):
        hdl = logging.StreamHandler(sys.stdout)
    else:
        try:
            hdl = logging.FileHandler(filename, mode='w')
        except IOError, e:
            sys.stderr.write('Can\'t open %s for logging: %s\n' % (filename, e.args[1]))
            hdl = logging.FileHandler('/dev/null', mode='w')
    frm = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    hdl.setFormatter(frm)
    log.addHandler(hdl)
    log.setLevel(logging.INFO)
    return log

def main():
    parser = OptionParser()
    parser.add_option('-p', '--port', type='int', dest='port',
                      help='serve in PORT', metavar='PORT',
                      default=DEFAULT_PORT)
    parser.add_option('-r', '--servicepath', type='string', dest='servicepath',
                      help='load service definitions from PATH',
                      metavar='PATH', default=DEFAULT_SERVICE_PATH)
    parser.add_option('-d', '--daemonize', action='store_true',
                      dest='daemonize', help='run in the background',
                      default=False)
    parser.add_option('-l', '--logfile', type='string', dest='logfile',
                      help='write log messages to file LOG. The default is to write  to stdout.',
                      metavar='LOG', default=None)
    (options, args) = parser.parse_args()

    log = setup_logging(options.logfile)

    if options.daemonize:
        daemonize.daemonize(pidfile=DEFAULT_PID_FILE)

    try:
        server = webvidaemon.WVDServer(options.port,
                                       webvidaemon.WVTPHandler,
                                       options.servicepath)
    except webvidaemon.WVError, e:
        log.error('%s. Exiting.' % str(e))
        return
    except socket.error, e:
        log.error('%s. Exiting.' % e[1])
        return

    try:
        asyncurl.loop(timeout=5)
    except KeyboardInterrupt:
        log.info('Crtl+C pressed. Shutting down.')

if __name__ == '__main__':
    main()
