#!/usr/bin/python3
## -*- coding: utf-8 -*-
#
# «Bare Server» - The webserver for Mythbuntu Bare console
#
# Copyright (C) 2011, Thomas Mashos, for Mythbuntu
#
#
# Mythbuntu-bare 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 2 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 application; if not, write to the Free Software Foundation, Inc., 51
# Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
##################################################################################

from http.server import CGIHTTPRequestHandler
from http.server import HTTPServer
import sys
import os
import logging
import signal

logger = logging.getLogger('mythbuntu-bare')
hdlr = logging.FileHandler('/var/log/mythbuntu-bare-server.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr) 
logger.setLevel(logging.WARNING)

ACTOR="<Webserver> "

class BareWebserver():

  def start_webserver(self, PORT):
    cgi_directories = ["/cgi-bin"]
    server_address=('',PORT)
    os.chdir("/var/lib/mythtv/bare/")
    httpd = HTTPServer(server_address, CGIHTTPRequestHandler)
    signal.signal(signal.SIGTERM, self.signal_handler)
    httpd.serve_forever()

  def signal_handler(self, signal, frame):
    httpd.server_close()
    logger.info(ACTOR+'Stopping BareServer')
    sys.exit(0)

if __name__ == "__main__":
  import configparser
  newconfig = configparser.ConfigParser()
  CONFIGFILE = "/var/lib/mythtv/bare/mythbuntu-bare.conf"
  logger.info(ACTOR+'Starting BareServer')
  try:
    newconfig.read(CONFIGFILE)
    serverport=int(newconfig.get("General", "serverport"))
    logger.info(ACTOR+'Setting communication port to: '+str(serverport))
  except:
    logger.error(ACTOR+'Cannot find communication port')
    sys.exit(1)
  try:
    BareWebserver().start_webserver(serverport)
    logger.info(ACTOR+'Bare Server Started')
  except IOError as xxx_todo_changeme: 
    (value,message) = xxx_todo_changeme.args 
    logger.error(ACTOR+'%s: %s' % (value, message))
    sys.exit(1)

